在SQL Server 2008中每组运行总计

时间:2017-02-22 17:39:21

标签: sql sql-server sql-server-2008

我的表格中有3列:组,日期和金钱。

Group    Day    Money    Column4 (Does not exist yet)
 A        1     $100     $100
 B        2     $500     $500
 A        3     $-150    $-50
 B        3     $900     $1400

我要做的是创建第4列,它实际上是每个组的运行总计。 A组的运行总数为(100,100-150 = 50)。

这在SQL Server 2008中是否可行?获取前3列的代码如下:

Select [Group], [Day], sum(money) as [Money]
From Table_Name
Group by [Group], [Day]

2 个答案:

答案 0 :(得分:1)

执行此操作的最佳方法是累积金额。也许是时候更新到更新版本的SQL Server了?

在SQL Server 2008中,您可以使用apply或相关子查询:

Select [Group], [Day], sum(money) as [Money],
       (select sum(t2.money)
        from table_name t2
        where t.group = t2.group and t2.day <= t.day
       ) as Column4
From Table_Name t
Group by [Group], [Day];

答案 1 :(得分:1)

您可以使用窗口函数sum来查找累计和:

select 
    t.*,
    sum(Money) over (partition by [group] order by [Day]) col4
from your_table t;

所以你的查询变为:

select t.*,
    sum([Money]) over (
        partition by [group] order by [Day]
        ) col4
from (
    select [Group],
        [Day],
        sum(money) as [Money]
    from Table_Name
    group by [Group],
        [Day]
    ) t;