在SQL Server中计算五年前的总和

时间:2016-07-20 07:39:13

标签: sql-server sql-server-2008 datetime sum date-arithmetic

我使用select:

Select year, month, par1, par2, par3, value 
from table1

生成此表:

enter image description here

现在,我想计算五年前的总和(这是60个月)。

结果应如下所示:

enter image description here

我该怎么做?

1 个答案:

答案 0 :(得分:1)

对于你的情况,因为表是字符串,我使用CTE为所需的计算制定日期列

; with
cte as
(
    select  *, date = convert(date, year + '-' + substring(month, 2, 2) + '-01', 121)
    from    table1
)
select  *
from    cte c
    outer apply
    (
        select  SumOfValue = sum(Value)
        from    cte x
        where   x.date  >= dateadd(month, -60, c.date)
        and x.date  <= c.date
    ) t

如果您需要sum()按其他列分组,请将条件添加到OUTER APPLY查询

编辑1:

select  *
from    cte c
    outer apply
    (
        select  SumOfValue = sum(x.Value)
        from    cte x
        where   x.date  >= dateadd(month, -60, c.date)
        and     x.parameter1 = c.parameter1
        and     x.parameter2 = c.parameter2
        and     x.date      <= c.date
    ) t