I am trying to create a query that uses a calculated field for another calculation in the same query but it’s giving me an error.
How can I accomplish this operation in an alternate manner.
Query :
SELECT MIN(q.order_created) AS first_ordered,
MAX(q.order_created) AS last_ordered,
SUM(IF(DATE_ADD(q.order_created,INTERVAL 12 MONTH) >= NOW(),pq.product_qty,0))/12 AS monthly_rate,
SUM(pq.product_qty) AS yearly_sales,
SUM((pq.product_cost_price * pq.product_qty) - pq.product_total_price ) AS **net_sold**,
SUM(pq.product_cost_price * pq.product_qty) AS **total_ordered**,
**100 - ((total_ordered - net_sold)/total_ordered )*100 AS discount**,
q.billing_account_id AS custid
FROM quotes q
LEFT JOIN products_quotes pq
ON q.id = pq.quote_id
WHERE pq.product_id = '28e96e3d-460f-49fc-7d52-4f390b86d6b8'
AND q.deleted = 0
AND pq.deleted = 0
GROUP BY q.billing_account_id
ORDER BY q.order_created
GROUP BY q.billing_account_id
ORDER BY q.order_created
Gives error : Unknown column ‘total_ordered’ in ‘field list’.
At first, you can’t use aggregation functions like SUM in that manner, because their final results will calculate while completing result set of the query, so even if it has no syntax error, the calculated result was not valid.
And second matter is that you can’t use alias names in the same select clause of same query, so you may want to use other way like this one:
Attention that as I told, syntax of this query is valid, but the results is NOT & the correct way is a little longer(like using subqueries).