SQL的行的序列总和

时间:2012-12-13 06:47:12

标签: sql sql-server-2008 tsql

请考虑下表。

ID          UserCount
----------- -----------
1           2
2           3
3           5

如何添加另一列(SequenceUserCount)并添加UserCount序列。

预期结果:

ID          UserCount   SequenceUserCount
----------- ----------- ------------------
1           2           2
2           3           5
3           5           10

2 个答案:

答案 0 :(得分:1)

你可以这样做:

;WITH CTE
AS
(
   SELECT *,
  ROW_NUMBER() OVER(ORDER BY usercount) rownum
  FROM @table1
) 
SELECT 
  c1.id, 
  c1.usercount,
  SequenceUserCount = (SELECT SUM(c2.usercount) 
                       FROM cte c2
                       WHERE c2.rownum <= c1.rownum)
FROM CTE c1;

SQL Fiddle Demo

这会给你:

| ID | USERCOUNT | SequenceUserCount  |
--------------------------------------
|  1 |         2 |        2           |
|  2 |         3 |        5           |
|  3 |         5 |       10           |

或:您可以使用JOIN代替相关子查询,如下所示:

;WITH CTE
AS
(
   SELECT *,
  ROW_NUMBER() OVER(ORDER BY usercount) rownum
  FROM @table1
) 
SELECT 
  c1.id, 
  c1.usercount,
  SequenceUserCount = SUM(c2.usercount) 
FROM CTE c1
INNER JOIN CTE c2 ON c2.rownum <= c1.rownum
GROUP BY c1.id, c1.usercount;

答案 1 :(得分:0)

试试这个

 select id,
   usercount       
   sum(usercount) over(order by usercount rows unbounded preceding) 
   as  sequenceusercount
 from Table