计算几周之间的折扣

时间:2015-03-14 09:43:34

标签: sql sql-server sql-server-2014

我有一张包含产品价格数据的表格,如下所示:

ProductId   RecordDate                  Price
46          2015-01-17 14:35:05.533     112.00
47          2015-01-17 14:35:05.533     88.00
45          2015-01-17 14:35:05.533     134.00

我已经能够按周和产品对数据进行分组,并使用以下查询:

SET DATEFIRST 1;

SELECT DATEADD(WEEK, DATEDIFF(WEEK, 0, [RecordDate]), 0) AS [Week], ProductId, MIN([Price]) AS [MinimumPrice]
FROM [dbo].[ProductPriceHistory]
GROUP BY DATEADD(WEEK, DATEDIFF(WEEK, 0, [RecordDate]), 0), ProductId
ORDER BY ProductId, [Week]

获得此结果:

Week                       Product    Price
2015-01-12 00:00:00.000    1          99.00
2015-01-19 00:00:00.000    1          98.00
2015-01-26 00:00:00.000    1          95.00
2015-02-02 00:00:00.000    1          95.00
2015-02-09 00:00:00.000    1          95.00
2015-02-16 00:00:00.000    1          95.00
2015-02-23 00:00:00.000    1          80.00
2015-03-02 00:00:00.000    1          97.00
2015-03-09 00:00:00.000    1          85.00
2015-01-12 00:00:00.000    2          232.00
2015-01-19 00:00:00.000    2          233.00
2015-01-26 00:00:00.000    2          194.00
2015-02-02 00:00:00.000    2          194.00
2015-02-09 00:00:00.000    2          199.00
2015-02-16 00:00:00.000    2          199.00
2015-02-23 00:00:00.000    2          199.00
2015-03-02 00:00:00.000    2          214.00

现在,对于每个产品,我希望获得最近两周值之间的差异,以便我可以计算折扣。我不知道如何将其写为SQL查询!

编辑: 预期的产出将是这样的:

Product    Price
1          -12.00
2          15.00

谢谢!

2 个答案:

答案 0 :(得分:2)

因为您使用的是Sql Server 2014,所以可以使用LAGLEAD窗口函数来执行此操作。

生成Row number以查找每个product的最后两周。

;WITH cte 
     AS (SELECT *, 
                Row_number()OVER(partition BY product ORDER BY weeks DESC)rn 
         FROM   Yourtable) 
SELECT product, 
       price 
FROM   (SELECT product, 
               Price=price - Lead(price)OVER(partition BY product ORDER BY rn) 
        FROM   cte a 
        WHERE  a.rn <= 2) A 
WHERE  price IS NOT NULL 

传统解决方案,可在Sql server 2012

之前使用
;WITH cte
     AS (SELECT *,
                Row_number()OVER(partition BY product
                    ORDER BY weeks DESC)rn
         FROM   Yourtable)
SELECT a.Product,
       b.Price - a.Price
FROM   cte a
       LEFT JOIN cte b
              ON a.Product = b.Product
                 AND a.rn = b.rn + 1
WHERE  a.rn <= 2
       AND b.Product IS NOT NULL 

答案 1 :(得分:1)

尝试此查询:

;WITH WeeklyPrice
AS (
    ... your query ...
), WeeklyPriceWithRowNum
AS (
    SELECT * 
    FROM (
        SELECT  w.ProductId, w.Price, 
            ROW_NUMBER() OVER(PARTITION BY w.ProductId ORDER BY w.Week DESC) AS RowNum
        FROM    WeeklyPrice w
    ) x
    WHERE x.RowNum <= 2
)
SELECT  pvt.ProductId, [1] AS LastPrice, [2] AS SecondLastPrice, [1] - ISNULL([2], 0) AS Diff
FROM    WeeklyPriceWithRowNum wp
PIVOT( MAX(wp.Price) FOR wp.RowNum IN ([1], [2]) ) pvt