简体   繁体   中英

Calculate Total Ending Quantity by using previous and next row value (LAG & LEAD) in SQL Server

Calculate Total Ending Quantity by using previous and next row value (LAG & LEAD) in SQL Server. Here is the input data.

Input Data

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

Expected Output Data/ Desired Result

"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]

Existing Query works for Beginning & Net Change columns. however, for column "Zero Beginning Qty" this code is not giving expected output.

Current Incorrect Results

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

You try to nest analytical functions, which is not allowed.

Based on your expected result all your calculations seem to be based on two values: the quantity in the previous row and the 1st row.

with cte as
 (
   select      Date, Account, Type, Quantity
    ,  LAG(Quantity, 1) OVER (ORDER BY Date) AS LagQty -- previous row
    ,  first_value(Quantity) OVER (ORDER BY Date) AS firstQty -- first row
   from        Tab
 )
select Date, Account, Type, Quantity
  ,LagQty as [Beginning Qty]
  ,Quantity - LagQty AS [Net_Change_Qty]
  ,LagQty - firstQty AS [Zero_Qty_Beginning]
  ,Quantity - firstQty AS [End_Qty]
from cte
order by    [Date]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM