Sql SUM一步一步指出

时间:2012-01-31 10:15:21

标签: sql sum

假设我有一张这样的表:

ID_points ID_team points date
1         1        2     1/15/2012
2         1        0     1/16/2012
3         1        -1    1/17/2012
4         1        3     1/18/2012
5         1        4     1/18/2012

现在,我想要做的是将点数相加,而不是所有点数,而不是一步一步,所以我可以得到一个漂亮的图表。

例如,我希望我的表看起来像这样(在我按ID过滤团队,并按日期ASC排序):

ID_points ID_team points date
1         1        2     1/15/2012
2         1        2     1/16/2012
3         1        1    1/17/2012
4         1        4     1/18/2012
5         1        8     1/18/2012

这可能与否?

2 个答案:

答案 0 :(得分:0)

declare @tbl table (ID_points int primary key, ID_team int, points int, [date] date)

insert into @tbl select 1,1,2,'1/15/2012'
union select 2,1,0,'1/16/2012'
union select 3,1,-1,'1/17/2012'
union select 4,1,3,'1/18/2012'
union select 5,1,4,'1/18/2012'


select t1.ID_points, t1.ID_team, sum(t2.points) points, t1.[date]
from @tbl t1
left join @tbl t2
    on t1.ID_points >= t2.ID_points
group by t1.ID_points, t1.ID_team, t1.[date]

答案 1 :(得分:0)

如果您使用的是支持窗口函数的DBMS,它就像:

一样简单
SELECT ID_points, 
       ID_team, 
       points, 
       sum(points) over (partition by id_team order by date) as running_poins
FROM the_table
ORDER BY id_team, date