2017-02-22 55 views
1

我的表中有3列:Group,Date和Money。SQL Server 2008中每個組的運行總數

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] 
+0

https://sqlperformance.com/2014/01/t-sql-queries/grouped-running-tota LS –

回答

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

您可以使用窗口函數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;