SQL Server / T-SQL中基于多个列的先前运行总计

时间:2018-11-15 05:11:19

标签: sql-server tsql

我正努力添加到SQL Server中具有运行总计的表中,希望得到您的帮助。

我有一个以这种方式开始的表:

EPDate             Item               BuyItem
----------------------------------------------
20150101           Mouse              10
20150101           Keyboard           100
20150202           Mouse              20
20150202           Keyboard           200

我要生成下表:

EPDate             Item        RunningTotal           Previous Running Total 
----------------------------------------------------------------------------
20150101           Mouse              10                        0
20150202           Mouse              30                        10
20150101           Keyboard           100                       0
20150202           Keyboard           300                       100

我需要“上一个运行总计”列的帮助,因为我实际上能够使用以下查询生成“运行总额”列:

SELECT 
    *,
    SUM() OVER(PARTITION BY Item, ORDER BY EPDate) AS RunningTotal
FROM
    MySampleTable
ORDER BY 
    Item DESC

但是,鉴于我在不同日期具有两个不同的类别(鼠标,键盘),该如何创建“上一个运行总计”列?

提前谢谢!

3 个答案:

答案 0 :(得分:2)

如何从运行总计中减去该值并按如下所示修改原始查询。

SELECT 
    *,
    SUM(BuyItem) OVER(PARTITION BY Item, ORDER BY EPDate) AS RunningTotal,
    SUM(BuyItem) OVER(PARTITION BY Item, ORDER BY EPDate) - BuyItem AS Previous Running Total
FROM
    MySampleTable
ORDER BY 
    Item DESC

答案 1 :(得分:1)

尝试这样

 SELECT *, SUM() OVER(PARTITION BY Item, ORDER BY EPDate) AS RunningTotal 
         , SUM() OVER(PARTITION BY Item, ORDER BY EPDate) - BuyItem  AS PreviousRunningTotal 
 FROM MySampleTable 

答案 2 :(得分:0)

您可以使用lag()功能

DEMO

SELECT *,SUM(buyItem) OVER(PARTITION BY Item ORDER BY EPDate) AS RunningTotal,
lag(BuyItem) over(PARTITION BY Item order by EPDate) as [Previous Running Total]
FROM MySampleTable order by item

输出:

d           item      buyItem     RunningTotal  Previous Running Total
20150101    Keyboard   100         100              0
20150202    Keyboard   200         300             100
20150101    Mouse       10         10              0
20150202    Mouse       20         30              10