【问题标题】:Previous Running Totals in SQL Server / T-SQL based on multiple columns以前在 SQL Server/T-SQL 中基于多列运行总计
【发布时间】:2018-11-15 05:11:19
【问题描述】:

我正在努力在 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

我需要有关 Previous Running Total 列的帮助,因为我实际上能够使用以下查询生成 RunningTotal 列:

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

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

提前谢谢你!

【问题讨论】:

    标签: sql-server tsql


    【解决方案1】:

    您如何从运行总计中减去该值并按如下方式修改您的原始查询。

    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
    

    【讨论】:

    • 到目前为止,这是一种比在运行总数上运行滞后更好的方法。更简洁、更快,并显示出对实际计算的了解。创建另一个帐户以便我可以再次投票会不会是错误的? ;)
    【解决方案2】:

    这样试试

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

    【讨论】:

    • 为什么要费心使用 LAG()?它只是运行总计减去当前值...
    • @MatBailie 没想到 :)
    【解决方案3】:

    你可以使用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
    

    【讨论】:

    • 非常感谢大家的意见 - 所有答案都有意义,尽管建议不要使用 LAG,但 fa06 的解决方案效果最好。我非常感谢你们提供的所有帮助!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-12-14
    • 2016-11-12
    • 2010-10-26
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多