我试图减去C和D列中的值,并将结果放在“Diff”列中。
Create table Test_Table
(Item INT,
[A] INT,
[B] INT,
[C] INT,
[D] INT,
[Date] Date
)
GO
INSERT INTO Test_Table
Values ('107', '136', '1', '3', '3', '03/21/16'),('109', '136', '1', '2', '2', '03/21/16'),
('110', '136', '1', '1', '1', '03/21/16'),('108', '136', '2', '10', '4', '03/21/16'),
('108', '136', '3', '10', '3', '03/25/16'),('108', '136', '4', '10', '3', '03/26/16'),
('115', '138', '5', '5', '3', '04/01/16'),('115', '138', '6', '5', '2', '04/04/16')
GO
从Test_Table中选择*
For Item 108:
In row 4: Subtratc C4 and D4 (10-4=6).
In row 5: Replace C5=10 with 6 and subtract two columns (6-3=3).
In row 6: Replace C6=10 with 3 and subtract two columns (3-3=0).
For Item 115:
In row 7: Subtratc C7 and D7 (5-3=2).
In row 8: Replace C8=5 with 2 and subtract two columns (2-2=0).
结果应该是这样的......
任何帮助都将不胜感激。
答案 0 :(得分:1)
WITH i AS
(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY item ORDER BY date) rn
FROM test_table
)
SELECT i.item, i.a, i.b,
io.c + COALESCE(dd, 0) c,
io.c + COALESCE(dd, 0) - i.d diff,
i.d, i.date
FROM i
CROSS APPLY
(
SELECT *
FROM i io
WHERE item = i.item
AND rn = 1
) io
CROSS APPLY
(
SELECT SUM(-d) dd
FROM i ii
WHERE item = io.item
AND rn < i.rn
) ii
在SQL Server 2014中,它更加简单高效:
SELECT item, a, b,
FIRST_VALUE(c) OVER (PARTITION BY item ORDER BY date) +
SUM(-d) OVER (PARTITION BY item ORDER BY date),
d, date
FROM test_table