Search code examples
mysqlsqlaggregate-functionsmysql-error-1054

Correlated subquery mysql


so i have a table with products

Product ID | Product Name
===========+===============
1          | Tissues
2          | Glass

I have a table with sales

Sale ID    | Product ID | Quantity | Price
===========+============+==========+=============
1          | 1          | 1        | 55
2          | 2          | 1        | 60

and i have a table of purchases

Batch ID | Total Value | Quantity | Product ID
=========+=============+==========+==================
1        | 100         | 100      | 1
2        | 10          | 50       | 2
3        | 1           | 1        | 2

So im trying to calculate the profit based on average cost using the query

SELECT tblsale.product_id, 
       tblproduct.product_name, 
       SUM(tblsale.`quantity`) qty,
       SUM(tblsale.`Price`*tblsale.`quantity`) sales, 
       (SELECT sum(total_value) / sum(quantity) VWAP 
        FROM tblpurchases 
        WHERE product_id = tblsale.product_id) average_price, 
       (average_price * qty) cost, 
       (sales-cost) profit 
FROM   tblsale, tblproduct 
WHERE tblproduct.product_id = tblsale.`product_id` 
GROUP by tblsale.`product_id`

But i can't seem to get it to work i get a 'average price' is an unknown column, how would I structure the query correctly


Solution

  • SQL doesn't support referencing a column alias in the same SELECT clause - that's why your average_price column is returning the 1054 error. You either have to do whatever operation you need in a subselect, derived table/inline view, or reuse the underlying logic where necessary. Here's an example of the reuse of logic:

       SELECT prod.product_id, 
              prod.product_name, 
              SUM(s.quantity) qty,
              SUM(s.Price * s.quantity) sales, 
              SUM(pur.total_value) / SUM(pur.quantity) average_price, 
              SUM(pur.total_value) / SUM(pur.quantity) * SUM(s.quantity) cost, 
              SUM(s.Price * s.quantity) - (SUM(pur.total_value) / SUM(pur.quantity) * SUM(s.quantity)) profit 
         FROM tblproduct prod 
    LEFT JOIN tblsale s ON prod.product_id = s.product_id
    LEFT JOIN tblpurchases pur ON pur.product_id = prod.product_id
     GROUP BY s.product_id
    

    My query is using ANSI-92 JOIN syntax, which I recommend over the ANSI-89 syntax your query uses. See this question for more details.