Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 30th, 2012  |  syntax: None  |  size: 2.06 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Correlated subquery mysql
  2. Product ID | Product Name
  3. ===========+===============
  4. 1          | Tissues
  5. 2          | Glass
  6.        
  7. Sale ID    | Product ID | Quantity | Price
  8. ===========+============+==========+=============
  9. 1          | 1          | 1        | 55
  10. 2          | 2          | 1        | 60
  11.        
  12. Batch ID | Total Value | Quantity | Product ID
  13. =========+=============+==========+==================
  14. 1        | 100         | 100      | 1
  15. 2        | 10          | 50       | 2
  16. 3        | 1           | 1        | 2
  17.        
  18. SELECT tblsale.product_id,
  19.        tblproduct.product_name,
  20.        SUM(tblsale.`quantity`) qty,
  21.        SUM(tblsale.`Price`*tblsale.`quantity`) sales,
  22.        (SELECT sum(total_value) / sum(quantity) VWAP
  23.         FROM tblpurchases
  24.         WHERE product_id = tblsale.product_id) average_price,
  25.        (average_price * qty) cost,
  26.        (sales-cost) profit
  27. FROM   tblsale, tblproduct
  28. WHERE tblproduct.product_id = tblsale.`product_id`
  29. GROUP by tblsale.`product_id`
  30.        
  31. SELECT prod.product_id,
  32.           prod.product_name,
  33.           SUM(s.quantity) qty,
  34.           SUM(s.Price * s.quantity) sales,
  35.           SUM(pur.total_value) / SUM(pur.quantity) average_price,
  36.           SUM(pur.total_value) / SUM(pur.quantity) * SUM(s.quantity) cost,
  37.           SUM(s.Price * s.quantity) - (SUM(pur.total_value) / SUM(pur.quantity) * SUM(s.quantity)) profit
  38.      FROM tblproduct prod
  39. LEFT JOIN tblsale s ON prod.product_id = s.product_id
  40. LEFT JOIN tblpurchases pur ON pur.product_id = prod.product_id
  41.  GROUP BY s.product_id
  42.        
  43. SELECT p.product_id, p.product_name
  44.          , SUM(s.quantity) number_of_sales
  45.          , SUM(s.price) total_profit
  46.          , SUM(pu.quantity) purchase_quantity
  47.          , SUM(pu.value) purchase_value
  48.          , (SUM(pu.quantity) - SUM(s.quantity)) number_in_stock
  49.          , (SUM(s.price) - SUM(pu.value)) profit
  50.          , (SUM(pu.value) / SUM(pu.quantity)) avarage_purchase_price
  51.       FROM product p
  52.  LEFT JOIN sales s ON s.product_id = p.product_id
  53.  LEFT JOIN purchase pu ON pu.product_id = p.product_id        
  54.   GROUP BY s.product_id, pu.product_id