【发布时间】:2018-03-25 06:13:17
【问题描述】:
使用 SQL Server 中的上一行和下一行值 (LAG & LEAD) 计算总结束数量。这是输入数据。
输入数据
Date Account Type Quantity
12/28/2007 A 2N 719
3/28/2008 A 2N 806
6/27/2008 A 2N 622
9/26/2008 A 2N 748
12/26/2008 A 2N 757
预期的输出数据/期望的结果
"Date" "Account" "Type" "Quantity" "Beginning Qty" "Net Change" "Zero Beginning Qty" "End Qty"
12/28/2007 A 2N 719 n/a n/a n/a 0
3/28/2008 A 2N 806 719 87 0 87
6/27/2008 A 2N 622 806 -184 87 -96
9/26/2008 A 2N 748 622 126 -96 29
12/26/2008 A 2N 757 748 9 29 38
select Date, Account, Type, Quantity
, LAG(Quantity, 1,0) OVER (ORDER BY Date) as [Beginning Qty]
, Quantity- LAG(Quantity,1,0) OVER (ORDER BY Date) AS [Net_Change_Qty]
, (Quantity- LAG(Sec_Share_Qty,1,0) OVER (ORDER BY Date)) + LEAD(Quantity, 1,0) OVER (ORDER BY Date)) as [Zero_Qty_Beginning]
,[Net_Change_Qty] + [Zero_Qty_Beginning] as [End Qty]
from Table
order by [Date]
现有查询适用于开始和净更改列。但是,对于“零起始数量”列,此代码没有给出预期的输出。
当前不正确的结果
Date Account Type Quantity Beginning Quantity Net Change Zero Beginning Qty End Quantity
12/28/2007 A 2N 719 0 719 1525 NULL
3/28/2008 A 2N 806 719 87 710 NULL
6/27/2008 A 2N 622 806 -184 564 NULL
9/26/2008 A 2N 748 622 126 883 NULL
12/26/2008 A 2N 757 748 9 765 NULL
【问题讨论】:
-
里面有问题吗?请edit您的问题将示例数据包含为 DDL+DML(创建表并插入语句),并显示所需的结果与您当前的结果。
-
“不工作”是什么意思“你想要什么结果?
标签: sql sql-server select partitioning