2011-12-22 113 views
0

樣品表ID:(num是一個關鍵所以不會有任何重複)創建累積和列

num 
1 
5 
6 
8 
2 
3 

我需要一個查詢,使這個: 所需的輸出: (應進行排序,並具有累積和列)

num cumulative 
1 1 
2 3 
3 6 
5 11 
6 17 
8 25 

Mysql的我有

Select num as n, 
     (select sum(num) from ID where num <= n) 
from ID order by n; 

我拿起這個例子在這個link但MySqlServer

+0

第一列是唯一的嗎? – 2011-12-22 14:12:17

+0

不,這一欄是簡單的值欄@OlegDok – soamazing 2011-12-22 14:13:52

+1

那麼如果沒有正確識別,那麼就沒有確切的決定 – 2011-12-22 14:15:49

回答

2

試試這個:

SELECT num,(SELECT SUM(num) FROM tab WHERE num<=t.num) AS CumulativeSum 
FROM tab t 
0

由於num是不是唯一的,你可能需要使用ROW_NUMBER在那裏得到一個唯一的編號,然後做總和:

declare @t as table (num int) 

insert into @t (num) values (1) 
insert into @t (num) values (5) 
insert into @t (num) values (6) 
insert into @t (num) values (7) 
insert into @t (num) values (2) 
insert into @t (num) values (3) 

;with rows as (
    select 
     num, 
     ROW_NUMBER() over (order by num) as Row 
    from @t 
) 
select num, (select sum(num) from rows where row <= r.row) 
from rows r