使用SQL Server

时间:2018-03-25 06:13:18

标签: sql sql-server select partitioning

使用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]

现有查询适用于Beginning&净变化列。但是,对于“Zero Beginning Qty”列,此代码未给出预期的输出。

当前不正确的结果

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

1 个答案:

答案 0 :(得分:0)

您尝试嵌套分析函数,这是不允许的。

根据您的预期结果,您的所有计算似乎都基于两个值:前一行和第一行的数量。

printf("\nYour Full Name is %s\n\n",first);