Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*assuming product data i.e.*/
- CREATE TABLE Product (ProductId INT, DateLaunched DATE)
- INSERT INTO Product (ProductId, DateLaunched)
- VALUES (1, '20190204'), (2, '20190211'), (3, '20190218')
- /*assuming transactional data i.e.*/
- CREATE TABLE Sale (SaleId INT, ProductId INT, QuantitySold INT, DateSold DATE)
- INSERT INTO Sale (SaleId, ProductId, QuantitySold, DateSold)
- VALUES (1, 1, 1, '20190129'), (2, 2, 2, '20190129'), (3, 2, 2, '20190129'), (4, 3, 3, '20190129'), (5, 3, 1, '20190129')
- /*query to prepare data*/
- /*make sure to declare indices for ProductId columns to improve performance*/
- SELECT
- subquery.ProductId
- ,subquery.DiffWeek
- ,SUM(subquery.QuantitySold) AS TotalQuantitySold
- FROM
- (SELECT
- s.SaleId
- ,s.ProductId
- ,s.QuantitySold
- ,s.DateSold
- ,p.DateLaunched
- ,ROUND((s.DateSold - p.DateLaunched) / 7, 0) AS DiffWeek
- FROM Sale AS s
- JOIN Product AS p ON s.ProductId = p.ProductId) AS subquery
- GROUP BY subquery.ProductId, subquery.DiffWeek
- /*query to get report data*/
- /*make sure to declare indices for ProductId columns to improve performance*/
- SELECT
- subquery1.ProductId
- ,SUM(subquery1.Sales_t) AS TotalSales_t
- ,SUM(subquery1.Sales_t_1) AS TotalSales_t_1 /*t-1*/
- ,SUM(subquery1.Sales_t_2) AS TotalSales_t_2 /*t-2*/
- ,SUM(subquery1.Sales_t_3) AS TotalSales_t_3 /*t-3*/
- /*, ...*/
- FROM (
- SELECT
- subquery0.ProductId
- ,CASE WHEN subquery0.DiffWeek = 0
- THEN subquery0.QuantitySold ELSE 0 END AS Sales_t
- ,CASE WHEN subquery0.DiffWeek = -1 /*t-1*/
- THEN subquery0.QuantitySold ELSE 0 END AS Sales_t_1
- ,CASE WHEN subquery0.DiffWeek = -2 /*t-2*/
- THEN subquery0.QuantitySold ELSE 0 END AS Sales_t_2
- ,CASE WHEN subquery0.DiffWeek = -3 /*t-3*/
- THEN subquery0.QuantitySold ELSE 0 END AS Sales_t_3
- /*, ...*/
- FROM (
- SELECT
- s.SaleId
- ,s.ProductId
- ,s.QuantitySold
- ,s.DateSold
- ,p.DateLaunched
- ,ROUND((s.DateSold - p.DateLaunched) / 7, 0) AS DiffWeek
- FROM Sale AS s
- JOIN Product AS p ON s.ProductId = p.ProductId
- ) AS subquery0
- ) AS subquery1
- GROUP BY subquery1.ProductId
Add Comment
Please, Sign In to add comment