我有两列,我想将每行的值添加到下一行。 我的表有两列和四行,如:
date users
2011-01-01 1
2011-02-02 1
2011-03-02 2
2011-04-02 4
我希望用户显示如下,并将每一行添加到它的上一行值:
用户:
1
2
4
8
MS SQL Server中是否有函数可以执行此操作?
感谢
答案 0 :(得分:2)
在SQL Server 2005及更高版本中(您没有指定版本),您可以使用两个CTE(公用表表达式)执行类似的操作 - 第一个名为UserSequence
的用于将数据放入一个订单,并给它一个序号(Sequence
),和第二个递归CTE(公用表表达式)来计算运行总数:
;WITH UserSequence AS
(
SELECT
Date, Users, ROW_NUMBER() OVER(ORDER BY Date) as 'Sequence'
FROM
dbo.YourTable
),
UserValues AS
(
SELECT
u.Users AS 'UserValue', u.Date, u.Sequence
FROM UserSequence u
WHERE Sequence = 1
UNION ALL
SELECT
u.Users + uv.UserValue AS 'UserValue', u.Date, u.Sequence
FROM UserSequence u
INNER JOIN UserValues uv ON u.Sequence = uv.Sequence + 1
)
SELECT
Date, Sequence, UserValue AS 'Users'
FROM
UserValues
ORDER BY
Sequence
那应该给你一个像这样的输出:
Date Sequence Users
2011-01-01 00:00:00.000 1 1
2011-02-02 00:00:00.000 2 2
2011-03-02 00:00:00.000 3 4
2011-04-02 00:00:00.000 4 8
答案 1 :(得分:2)
With cte_Test(Sequence,Name,Value)
As
(
select ROW_NUMBER() OVER(ORDER BY value) as 'Sequence' ,name,value from test
)
select t1.Name,sum(T2.Value) AS Value from cte_Test t1
cross JOIN cte_Test t2 where t2.Sequence <= t1.Sequence
group BY t1.Name
order by 2
答案 2 :(得分:1)
以下是您可以这样做的方法:
set @total_users = 0;
select users, @total_users:=@total_users + users as total_users from tablename;
答案 3 :(得分:1)
这可以通过Cross Join实现。如果您的表列是按Asc顺序。
select <T1.Text>,sum(T2.Value) AS 'Commulative Value' from <Your Table name>t1
cross JOIN <Your Table name> t2 where t2.value<= t1.value
group BY t1.text
order by value
答案 4 :(得分:0)
这是ANSI SQL中的解决方案:
SELECT users + lag(users) over (order by users) FROM your_table ORDER BY users
适用于PostgreSQL,Oracle,DB2和Teradata(SQL Server确实有窗口函数,但遗憾的是不是lag()函数)