每行添加 SQL 中的总值

Add per row the total value in SQL

在 SQL Server 2014 中,我尝试像这样计算每行每场比赛的价值:

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

您可以使用累计和:

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

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

如果你在 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

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

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