在SQL中添加每行的总值

时间:2016-01-06 11:58:37

标签: sql sql-server sql-server-2014

在SQL Server 2014中,我尝试计算每行每个游戏的值,如下所示:

enter image description here

有人知道这是否可能以及如何实现?

3 个答案:

答案 0 :(得分:3)

您可以使用累积总和:

select [Order], Game, Points,
       sum(Points) over (partition by Game order by  [Order]) as CumePoints
from t;

您应该避免对表名或列名使用保留字和关键字。换句话说,Order是列名的错误名称,因为它需要进行转义。

答案 1 :(得分:2)

如果您在T-SQL

中执行此操作,我就会这样做
if object_ID('tempdb..#Temp') IS NOT NULL drop table #Temp

create table #Temp (id int, Game nvarchar(100), Points int)

insert into #Temp (id, Game, Points)
values
(1, 'A', 1),
(2, 'A', 2),
(3, 'B', 5),
(4, 'B', 5),
(5, 'C', 4),
(6, 'C', 8)

select id, 
   Game, 
   Points, 
   SUM(Points) over (partition by Game order by id) 
from #Temp

答案 2 :(得分:0)

旧的解决方案是使用这样的查询:

SELECT 
    t1.id, t1.Game, t1.Points, SUM(t2.Points) [Points (Add)]
FROM 
    yourTable t1 JOIN
    yourTable t2 ON t1.Game = t2.Game AND t1.id >= t2.id
GROUP BY 
    t1.id, t1.Game, t1.Points