如何将多个月的数据转换为多个列

时间:2018-06-06 19:51:34

标签: sql-server sql-server-2008 tsql sql-server-2014

我有一个示例查询,如下所示,

SELECT SUM(Test) AS TotalLastMonth
FROM Table
WHERE  date >=DATEADD(MONTH, -1, getdate())
GROUP BY InvoiceNo

结果:

    22
    12
    34
    21
    16
    10
    18

我正在尝试将多个月的数据检索到多个列中。示例输出

TotalLastMonth TotalLast6Months TotalLast12Months
10              22                   97
12              24                   57
15              30                   63
21              42                   78
25              50                   75

1 个答案:

答案 0 :(得分:0)

条件聚合可行......

select 
     TotalLastMonth = sum(case when date >= dateadd(month,-1,getdate()) then Test end)
    ,TotalLast6Months = sum(case when date >= dateadd(month,-6,getdate()) then Test end)
    ,TotalLast6Months = sum(case when date >= dateadd(month,-12,getdate()) then Test end)

如果您想要在本月之外的整月,请使用您的DATEADD逻辑来获取本月的第一个月以及该月的最后一个月。

select
     --total last month, not including this month 
     TotalLastMonth = sum(case when date >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0) and date < DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) then Test end)
     --total last 6 months not including this month
    ,TotalLast6Months = sum(case when date >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-6, 0) and date <  DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) then Test end)
     --total last 12 months not including this month
    ,TotalLast6Months = sum(case when date >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-12, 0) and date <  DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) then Test end)