带日期的动态SQL查询

时间:2017-12-28 14:23:24

标签: sql sql-server

我有一个SQL查询,它正在创建一个PIVOT表。

就是这样。

SELECT *
FROM (
  SELECT
   Name
  ,Year
  ,sum(Payment) as TotalPayment  
  FROM Orders
  group by Name,Date
 ) as Tablo
 PIVOT
 (
    SUM(TotalPayment)
    FOR Date IN ([2009-11],[2009-12],[2010-01])
 )
 AS p

它每月支付总额,并且每个月都会手动添加年度月份。我需要动态地做。

如何使用循环或类似的SQL查询从表中动态获取月份?

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

我建议您使用relative时间,而不是absolute。通过这种方式,您的查询始终是最新的。在这里,我在SQL Fiddle

上发布了一个示例

MS SQL Server 2014架构设置

create table t ( d date, i int );
insert into t values
( '2016-01-01', 100 ),
-- ... some other data
( '2017-12-13', 100 );

我使用CTE逐步编写查询:

with 
cooked as          --change to relative months (from today)
( select datediff(MONTH,getdate(), d ) as dif, i
  from t
),
filtered as        --just take the last 12 months
( select dif as Date, i as TotalPayment
  from cooked
  where dif > -12
)
select *           --pivoting
from filtered
PIVOT
 (
    SUM(TotalPayment)
    FOR Date IN ([-11],[-10],[-9],[-8],
                 [-7],[-6],[-5],[-4],
                 [-3],[-2],[-1],[0])
 )
 AS p

此处为 Results ,其中[0]表示此飞蛾,[-11]表示12个月前:

| -11 | -10 |  -9 |  -8 |  -7 |  -6 |  -5 |  -4 |  -3 |  -2 |  -1 |   0 |
|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|
| 500 | 500 | 100 | 100 | 100 | 100 | 100 | 100 | 100 | 100 | 100 | 100 |