简体   繁体   中英

How Do I do A Cummulative Subtraction in SQL Views?

I have an SQL view that has two fields. I want to calculate reducing balance in weekly terms.

TableID  item_no    Qty_shp     Qty_Stk  Balance    posting_date    
1        WTR234       28         500       472       2015/03/09
2        WTR234       42         472       430       2015/03/15
3        WTR234       100        500       400       2015/03/16
4        WTR234       50         400       350       2015/03/22

As shown in the table above, I need to be able to calculate the balance on these items on a weekly terms as the Qty_Stk reverts to a new value at the beginning of a new week being Monday.


From comment of OP

TableID item_no Qty_shp Qty_O   Qty_Stk Balance posting_date    
1       WTR234  28      500     500     472     2015/03/09  
2       WTR234  42      500     472     430     2015/03/15  
3       WTR234  100     500     500     400     2015/03/16  
4       WTR234  50      500     400     350     2015/03/22

This can be solved using the aggregate function sum() with an over () clause. In the query I only partitioned the data based on week, but maybe you want to include the item_no as part of the partitioning too if there are multiple products.

I think this query should give you the correct results (it did for me using your limited sample data).

Edit: i used the setting SET DATEFIRST 1 when I tried it.

select 
    TableID,
    item_no,
    Qty_shp,
Qty_Stk = qty_o - isnull(
   sum(qty_shp) over (
      partition by datepart(week, posting_date) 
      order by posting_date 
      rows between unbounded preceding and 1 preceding
      )
   ,0),
    Balance = qty_o - sum(qty_shp) over (
       partition by datepart(week, posting_date) 
       order by posting_date
    ),
    posting_date    
from your_table

This gave me the following output:

TableID     item_no    Qty_shp     Qty_Stk     Balance     posting_date
----------- ---------- ----------- ----------- ----------- ------------
1           WTR234     28          500         472         2015-03-09
2           WTR234     42          472         430         2015-03-15
3           WTR234     100         500         400         2015-03-16
4           WTR234     50          400         350         2015-03-22

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