- Correlated subquery mysql
- Product ID | Product Name
- ===========+===============
- 1 | Tissues
- 2 | Glass
- Sale ID | Product ID | Quantity | Price
- ===========+============+==========+=============
- 1 | 1 | 1 | 55
- 2 | 2 | 1 | 60
- Batch ID | Total Value | Quantity | Product ID
- =========+=============+==========+==================
- 1 | 100 | 100 | 1
- 2 | 10 | 50 | 2
- 3 | 1 | 1 | 2
- 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`
- 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
- SELECT p.product_id, p.product_name
- , SUM(s.quantity) number_of_sales
- , SUM(s.price) total_profit
- , SUM(pu.quantity) purchase_quantity
- , SUM(pu.value) purchase_value
- , (SUM(pu.quantity) - SUM(s.quantity)) number_in_stock
- , (SUM(s.price) - SUM(pu.value)) profit
- , (SUM(pu.value) / SUM(pu.quantity)) avarage_purchase_price
- FROM product p
- LEFT JOIN sales s ON s.product_id = p.product_id
- LEFT JOIN purchase pu ON pu.product_id = p.product_id
- GROUP BY s.product_id, pu.product_id