2011-02-12 81 views
0

我有兩列,我想將每一行的值添加到下一行。 我有兩列4行表是這樣的:計數sql行,將每一行的值添加到下一行

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

對不起是的,我應該用代碼標記做到這一點。 – m0j1 2011-02-12 08:50:36

回答

2

在SQL Server 2 005及以上(您沒有指定您的版本),您可以使用兩個CTE(公用表表達式)做這樣的事情 - 第一個叫做UserSequence的CTE將數據放入訂單並給它一個序號(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

這裏是你如何能做到這一點:

set @total_users = 0; 
select users, @total_users:[email protected]_users + users as total_users from tablename; 
+0

這不是有效的SQL。這是什麼數據庫系統? MySQL數據庫: – 2011-02-12 08:46:20

+0

MySQL。測試它,它的工作原理。 – 2011-02-12 08:53:19

+0

在SQL Server中有一個類似的(無證的和不保證的)技術叫做「quirky update」 – 2011-02-12 09:01:31

0

這是ANSI SQL的解決方案:

 
SELECT users + lag(users) over (order by users) 
FROM your_table 
ORDER BY users 

作品在PostgreSQL裏,甲骨文,DB2和Teradata(SQL服務器確實有窗口函數,但不幸的是不是lag()函數)

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 
1

這是可能通過交叉加入。如果您的表格列處於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 
相關問題