简体   繁体   English

每行将SQL中的总值相加

[英]Add per row the total value in SQL

In SQL Server 2014 I try to count a value per game per row like this: 在SQL Server 2014中,我尝试像这样计算每游戏每行的值:

在此处输入图片说明

Does anybody know if this is possible and how? 有人知道这是否可行吗?

You can use a cumulative sum: 您可以使用累计总和:

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

You should avoid using reserved words and keywords for table or column names. 您应该避免为表或列名称使用保留的单词和关键字。 In other words, Order is a bad name for a column name, because it needs to be escaped. 换句话说, Order是列名的坏名字,因为它需要被转义。

This is how i would have done it, if you would do it in T-SQL 如果您在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

An old solution for this is to use a query like this: 一个旧的解决方案是使用这样的查询:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM