SQL Server Cumulative Sum by Group

前端 未结 1 1643
没有蜡笔的小新
没有蜡笔的小新 2020-12-01 09:32

I have a table (SQL Server 2005) of this format:

dummy_id, date_registered, item_id, quantity, price

and I want to add a new column (

相关标签:
1条回答
  • 2020-12-01 10:19

    In SQL Server 2005, I would do this using a correlated subquery:

    select dummy_id, date_registered, item_id, quantity, price,
           (select sum(quantity)
            from t t2
            where t2.item_id = t.item_id and
                  t2.date_registered <= t.date_registered
           ) as cumulative
    from table t;
    

    If you actually want to add this into a table, you need to alter the table to add the column and then do an update. If the table has inserts and updates, you will need to add a trigger to keep it up-to-date. Getting it through a query is definitely easier.

    In SQL Server 2012, you can do this using the syntax:

    select dummy_id, date_registered, item_id, quantity, price,
           sum(quantity) over (partition by item_id order by date_registered) as cumulative
    from table t;
    
    0 讨论(0)
提交回复
热议问题