Guest User

Untitled

a guest
Jan 22nd, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. /*assuming product data i.e.*/
  2. CREATE TABLE Product (ProductId INT, DateLaunched DATE)
  3. INSERT INTO Product (ProductId, DateLaunched)
  4. VALUES (1, '20190204'), (2, '20190211'), (3, '20190218')
  5.  
  6. /*assuming transactional data i.e.*/
  7. CREATE TABLE Sale (SaleId INT, ProductId INT, QuantitySold INT, DateSold DATE)
  8. INSERT INTO Sale (SaleId, ProductId, QuantitySold, DateSold)
  9. VALUES (1, 1, 1, '20190129'), (2, 2, 2, '20190129'), (3, 2, 2, '20190129'), (4, 3, 3, '20190129'), (5, 3, 1, '20190129')
  10.  
  11. /*query to prepare data*/
  12. /*make sure to declare indices for ProductId columns to improve performance*/
  13. SELECT
  14. subquery.ProductId
  15. ,subquery.DiffWeek
  16. ,SUM(subquery.QuantitySold) AS TotalQuantitySold
  17. FROM
  18. (SELECT
  19. s.SaleId
  20. ,s.ProductId
  21. ,s.QuantitySold
  22. ,s.DateSold
  23. ,p.DateLaunched
  24. ,ROUND((s.DateSold - p.DateLaunched) / 7, 0) AS DiffWeek
  25. FROM Sale AS s
  26. JOIN Product AS p ON s.ProductId = p.ProductId) AS subquery
  27. GROUP BY subquery.ProductId, subquery.DiffWeek
  28.  
  29. /*query to get report data*/
  30. /*make sure to declare indices for ProductId columns to improve performance*/
  31. SELECT
  32. subquery1.ProductId
  33. ,SUM(subquery1.Sales_t) AS TotalSales_t
  34. ,SUM(subquery1.Sales_t_1) AS TotalSales_t_1 /*t-1*/
  35. ,SUM(subquery1.Sales_t_2) AS TotalSales_t_2 /*t-2*/
  36. ,SUM(subquery1.Sales_t_3) AS TotalSales_t_3 /*t-3*/
  37. /*, ...*/
  38. FROM (
  39. SELECT
  40. subquery0.ProductId
  41. ,CASE WHEN subquery0.DiffWeek = 0
  42. THEN subquery0.QuantitySold ELSE 0 END AS Sales_t
  43. ,CASE WHEN subquery0.DiffWeek = -1 /*t-1*/
  44. THEN subquery0.QuantitySold ELSE 0 END AS Sales_t_1
  45. ,CASE WHEN subquery0.DiffWeek = -2 /*t-2*/
  46. THEN subquery0.QuantitySold ELSE 0 END AS Sales_t_2
  47. ,CASE WHEN subquery0.DiffWeek = -3 /*t-3*/
  48. THEN subquery0.QuantitySold ELSE 0 END AS Sales_t_3
  49. /*, ...*/
  50. FROM (
  51. SELECT
  52. s.SaleId
  53. ,s.ProductId
  54. ,s.QuantitySold
  55. ,s.DateSold
  56. ,p.DateLaunched
  57. ,ROUND((s.DateSold - p.DateLaunched) / 7, 0) AS DiffWeek
  58. FROM Sale AS s
  59. JOIN Product AS p ON s.ProductId = p.ProductId
  60. ) AS subquery0
  61. ) AS subquery1
  62. GROUP BY subquery1.ProductId
Add Comment
Please, Sign In to add comment