[英]Subtract the difference from the others in the current row from the previous value in the column
Good afternoon: I want to get the following result.下午好:我想得到以下结果。 to subtract the remainder of the difference that must be shipped.减去必须运送的差额的剩余部分。 I try through the LAG function, It turns out.我尝试通过 LAG function,结果是。 but somehow everything is crooked.但不知何故,一切都是歪的。 Tell me how you can write it in SQL more elegantly.告诉我如何更优雅地写在 SQL 中。
CREATE TABLE TestTable(
[id] INT IDENTITY,
[productid] INT,
[name] NVARCHAR(256),
[ordered] DECIMAL(6,3),
[delivered] DECIMAL(6,3),
[remainder] DECIMAL(6,3));
INSERT INTO TestTable ([productid], [name], [ordered], [delivered], [remainder])
VALUES (712054, 'Product OSFNS', 253, 246.005, 13.255),
(712054, 'Product OSFNS', 186, 183.63, 13.255),
(712054, 'Product OSFNS', 196.8, 193.745, 13.255),
(712054, 'Product OSFNS', 480, 477.025, 13.255)
And the query:和查询:
WITH CTE_diff AS
(SELECT
T1.[id]
,T1.[productid]
,T1.[name]
,T1.[ordered]
,T1.[delivered]
,T1.[remainder]
,LAG(T2.[ordered] - T2.[delivered], 1, T1.[ordered] - T1.[delivered])
OVER (ORDER BY T2.[productid]) as R
FROM TestTable T1 JOIN TestTable T2
ON T1.id = T2.id - 1
UNION
SELECT *
FROM (
SELECT TOP(1)
T1.[id]
,T1.[productid]
,T1.[name]
,T1.[ordered]
,T1.[delivered]
,T1.[remainder]
,LEAD(T2.[ordered] - T2.[delivered], 1, T1.[ordered] - T1.[delivered])
OVER (ORDER BY T2.[productid]) as R
FROM TestTable T1 JOIN TestTable T2
ON T1.id = T2.id
ORDER BY T1.id DESC
) as tbl)
SELECT * FROM CTE_diff;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.