需要计算行之间的总和

时间:2017-01-20 07:35:43

标签: sql sql-server sql-server-2008 sql-server-2012

我需要帮助以下逻辑,我已经尝试了我的结束,但无法解决此问题。 我的输入表格如下:

Months  Amount
Dec-15      720030
Jan-16      763236
Feb-16      795555
Mar-16      829252
Apr-16      856052

我需要计算如下的值,它将是动态的,因为月份将根据当前日期增加。输出:

+---------------------------------------------------------+
| Months      Amount      Formula         Expected Amount |
+---------------------------------------------------------+
| 15-Dec      720030      Dec-15          720030          |
| 16-Jan      763236      Dec-15+Jan-16   1483266         |
| 16-Feb      795555      Jan-16+Feb-16   1558791         |
| 16-Mar      829252      Feb-16+Mar-16   1624807         |
| 16-Apr      856052      Mar-16+Apr-16   1685304         |
+---------------------------------------------------------+

2 个答案:

答案 0 :(得分:0)

使用LAG()

SELECT Months, Amount,
       CONVERT(varchar, MONTHS, 101) +     -- replace 101 with correct format mask
       CASE WHEN CONVERT(varchar, LAG(Months , '') OVER (ORDER BY Months), 101) <> ''
            THEN ' + ' + CONVERT(varchar, LAG(Months, '') OVER (ORDER BY Months), 101)
            ELSE '' END AS Formula,
       Amount + LAG (Amount, 0) OVER (ORDER BY Months) AS [Expected Amount]
FROM yourTable

答案 1 :(得分:0)

我首先创建了一个临时表,其中包含额外的列“ID”。 ID是使用ROW_NUMBER()函数创建的。然后,使用while循环我遍历表并在当前金额中添加金额的先前值

代码如下。

select month, amount, ROW_NUMBER() over(order by month) ID 
into New_Table from Your_Table

declare @a int
set @a = 1;
    while @a <= (select max(ID) from New_Table)
        begin
            IF @a = 1
            select month, amount, amount Expected_Amount from New_Table where ID = @a;
            ELSE
            select month, amount, amount + (select amount from New_Table where ID = (@a-1)) Expected_Amount from New_Table where ID = @a;
set @a = @a + 1;
end;