累积SUM SQL Server 2008

时间:2014-08-12 10:32:13

标签: sql-server-2008 tsql

我有桌子

Year    Month   Week        Amount     
-------------------------------------
2014    1        1       25501000,00       
2014    1        2      118852000,00       
2014    1        3      135764000,00       
2014    1        4      153967000,00       
2014    1        5      157648000,00       

我需要选择另外一行,每周累计SUM金额:

Year    Month   Week       ApvdAmtWeek  SUMamount
---------------------------------------------------
2014      1      1          25501000,00        x1
2014      1      2         118852000,00        x1+x2
2014      1      3         135764000,00        x1+x2+x3 
2014      1      4         153967000,00        x1+x2+x3+x4 
2014      1      5         157648000,00        x1+x2+x3+x4+x5

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

这可能会对你有帮助。

DECLARE @TAB TABLE (YEAR INT, MONTH INT,  WEEK INT,AMOUNT BIGINT)
INSERT INTO @TAB VALUES
(2014,1,1,2550100000) ,    
(2014,1,2,11885200000),     
(2014,1,3,13576400000),     
(2014,1,4,15396700000),     
(2014,1,5,15764800000)

- 查询:

SELECT  Year,Month,Week,SUM(AMOUNT) ApvdAmtWeek FROM (
        SELECT  B.YEAR,B.MONTH,B.WEEK,A.AMOUNT 
        FROM    @TAB A,@TAB B 
        WHERE   A.WEEK <= B.WEEK) LU
        GROUP BY YEAR,MONTH,WEEK

- 结果:

enter image description here

答案 1 :(得分:0)

一种方式,因为没有ID而不漂亮:

;with T as (
    select row_number() over (order by year, Month, Week) rn, Year, Month, Week, Amount
    from thetable
) 
select T.rn, T.Year, T.Month, T.Week, sum(T2.Amount) from T
    inner join (select 
        rn, Year, Month, Week, Amount from T
    ) T2 on T.rn >= T2.rn
group by T.rn, T.Year, T.Month, T.Week
order by T.rn