如何对结果和当前值进行对角线减法

时间:2019-06-20 05:31:14

标签: sql sql-server tsql

我有一个产品表,我想用价格列进行锯齿形减法

我尝试了以下查询,但对我而言不起作用

SELECT price
,price - (SELECT COALESCE(lag(price) OVER (ORDER BY ProductID),price)  AS PayableInQuarter  
FROM @Products WHERE ProductID=1) from @Products

创建表的代码

DECLARE @Products TABLE (ProductID INT, ProductName VARCHAR(20), Price int)

INSERT INTO @Products VALUES (1, 'A', 1000)
INSERT INTO @Products VALUES (2, 'B', 5000)
INSERT INTO @Products VALUES (3, 'C', 9000)
INSERT INTO @Products VALUES (4, 'E', 12000)

SELECT * FROM @Products

预期输出如下

| ProductId | ProductName | Price | Difference |
|-----------|-------------|-------|------------|
|         1 |           A |  1000 |       1000 |
|         2 |           B |  5000 |       4000 |
|         3 |           C |  9000 |       5000 |
|         4 |           E | 12000 |       7000 |

1 个答案:

答案 0 :(得分:3)

我们可以在ROW_NUMBER的帮助下尝试采取不同的滚动方式:

WITH cte AS (
    SELECT *,
        ROW_NUMBER() OVER (ORDER BY ProductID) rn,
        COUNT(*) OVER () cnt
    FROM @Products
)

SELECT
    ProductID,
    ProductName,
    Price,
    (CASE WHEN rn % 2 = 0 THEN 1.0 ELSE -1.0 END) *
    (SELECT SUM(CASE WHEN (t2.cnt - t2.rn) % 2 = 0
                     THEN t2.Price ELSE -1.0*t2.Price END)
     FROM cte t2
     WHERE t2.ProductID <= t1.ProductID) AS Difference
FROM cte t1
ORDER BY
    ProductID;

Demo