使用SQL计算基于添加或减去条件的新列中的运行总计

时间:2018-03-13 17:03:21

标签: sql sql-server conditional partitioning running-total

我正在尝试根据帐户和日期在另一列中的值加/减计算运行总计。

示例

Data 
ID     Account  Date         Operation         Qty              Running_Total 
1       A       01/01/2018       plus           10              10
2       A       01/02/2018       plus           20              30 
3       A       01/03/2018       minus           5              20
4       A       01/03/2018       minus           5              20
5       A       01/04/2018       plus           30              50
6       B       01/01/2018       plus           15              15

总数

Code: 
select ID, Date, Operation, Total, 
              case when Operation = 'Use Table B' then TableB.RunningTotalQty 
              else
              SUM( case when Operation = 'plus' then  Qty 
                   else case when Operation = 'minus' then -Qty end) 
              OVER (PARTITION BY Account ORDER BY Date)  end
            From TableA A left Join TableB B 
on A.ID = B.ID ...

1 个答案:

答案 0 :(得分:1)

这是对问题的原始版本的回答。

case进入sum()

select ID, Date, Operation, Total, 
       sum(case when Operation = 'plus' then qty else - qty end) over
           (partition by Account order by Date) as Running_Total
From TableA  ;

这只假设两个操作。如果你还有更多:

select ID, Date, Operation, Total, 
       sum(case when Operation = 'plus' then qty
                then Operation = 'minus' then - qty
                else 0
           end) over
           (partition by Account order by Date) as Running_Total
From TableA  ;