views:

45

answers:

4

The exact error I am getting is: "Unknown column 'trans_paid' in 'where clause'"

My query ($from_date and $to_date are correctly formatted):

SELECT 
   o.order_id,
   o.order_po_no,
   o.order_ship_date,
   acct.acct_company,
   SUM( ROUND( i.item_qty * i.item_price, 2 ) ) AS item_amount, (
      SELECT SUM( trans_amount )
        FROM transactions
      WHERE order_id = o.order_id
        AND trans_pending =0
        AND trans_date >= '$from_date'
        AND trans_date <= '$to_date'
   ) AS trans_paid
 FROM orders AS o
     INNER JOIN accounts AS acct ON o.acct_id = acct.acct_id
     INNER JOIN items AS i ON o.order_id = i.order_id
   WHERE (o.order_status =7 or o.order_status = 4)
      AND trans_paid IS NOT NULL
      AND acct.is_wholesale =1
      AND acct.acct_company LIKE '%".$_POST['company']."%'
 GROUP BY o.order_id
+4  A: 

You can't reference aliased columns in the SELECT cause from the WHERE clause. You'll have to wrap it in a subquery if you want to filter on it.

JamesMLV
A: 

An alias name to be used in the Where clause has to be declared in the FROM clause...You simply renamed a column not actually rename an object such as a table.

Ehsan
+3  A: 

Standard SQL doesn't allow you to refer to aggregate columns in the WHERE clause. You need to move the trans_paid condition to a HAVING clause to make it work.

Change

WHERE (o.order_status =7 or o.order_status = 4)
    AND trans_paid IS NOT NULL
    AND acct.is_wholesale =1
    AND acct.acct_company LIKE '%".$_POST['company']."%'
GROUP BY o.order_id

to

WHERE (o.order_status =7 or o.order_status = 4)
    AND acct.is_wholesale =1
    AND acct.acct_company LIKE '%".$_POST['company']."%'
GROUP BY o.order_id
HAVING trans_paid IS NOT NULL
Hammerite
A: 

use this query:

SELECT 
   o.order_id,
   o.order_po_no,
   o.order_ship_date,
   acct.acct_company,
   SUM( ROUND( i.item_qty * i.item_price, 2 ) ) AS item_amount,
   trans_paid
   FROM orders AS o
   LEFT JOIN 
   (SELECT SUM( trans_amount ) AS trans_paid
    FROM 
    WHERE trans_pending =0
    AND trans_date >= '$from_date'
    AND trans_date <= '$to_date'
   ) temp
   USING order_id

   INNER JOIN accounts AS acct ON o.acct_id = acct.acct_id
   INNER JOIN items AS i ON o.order_id = i.order_id
   WHERE (o.order_status =7 or o.order_status = 4)
      AND trans_paid IS NOT NULL
      AND acct.is_wholesale =1
      AND acct.acct_company LIKE '%".$_POST['company']."%'
 GROUP BY o.order_id
rahim asgari