如何在 SQL 服务器中每月调整温度?

How to pivot temperature per month in SQL Server?

我可以这样算出每年的平均气温:

select Ville, 
       AVG(Temperature) as Temperature 
from Meteo 
where DateDonnees between '2011-01-01' and '2012-01-01' 
group by  Ville

问题是我想知道每个月的温度。

所以我找到了一个 post 来解释如何做到这一点:

select * from(
select Ville, Temperature as Temperature from Meteo where DateDonnees between '2011-01-01' and '2012-01-01' group by  Ville
)
pivot(
cast(AVG(Temperature)) AS DECIMAL(4, 1) for DateDonnees in (
    1 JAN, 2 FEB, 3 MAR, 4 APR, 5 MAY, 6 JUN,
    7 JUL, 8 AUG, 9 SEP, 10 OCT, 11 NOV, 12 DEC)
))

并抛出 "Incorrect syntax near the keyword 'pivot'." 错误。

这是我希望看到的结果:

MONTH 函数可以放置在横向连接中,然后在 CASE 逻辑中用于透视月份。像这样

select Ville as City, 
       avg(case when mo.mon=1 then Temperature else 0 end) Jan,
       avg(case when mo.mon=2 then Temperature else 0 end) Feb,
       avg(case when mo.mon=3 then Temperature else 0 end) Mar,
       avg(case when mo.mon=4 then Temperature else 0 end) Apr,
       avg(case when mo.mon=5 then Temperature else 0 end) May,
       avg(case when mo.mon=6 then Temperature else 0 end) Jun,
       avg(case when mo.mon=7 then Temperature else 0 end) Jul,
       avg(case when mo.mon=8 then Temperature else 0 end) Aug,
       avg(case when mo.mon=9 then Temperature else 0 end) Sep,
       avg(case when mo.mon=10 then Temperature else 0 end) Oct,
       avg(case when mo.mon=11 then Temperature else 0 end) Nov,
       avg(case when mo.mon=12 then Temperature else 0 end) [Dec]
from Meteo m
     cross apply
     (select month(m.DateDonnees) mon) mo
where DateDonnees between '2011-01-01' and '2012-01-01' 
group by Ville;

我会推荐条件聚合:

select city,
    avg(case when datedonnees >= '20200101' and datedonnees < '20200201' then temperature end) jan,
    avg(case when datedonnees >= '20200201' and datedonnees < '20200301' then temperature end) feb,
    avg(case when datedonnees >= '20201201' and datedonnees < '20200401' then temperature end) mar,
    ...
    avg(case when datedonnees >= '20201201' and datedonnees < '20210101' then temperature end) dec
from meteo
where datedonnees >= '20200101' and datedonnees < '20210101'
group by city

我们可以使用 month() 稍微缩短语法,但它可能不如 half-open 间隔有效:

select city,
    avg(case when month(datedonnees) =  1 then temperature end) jan,
    avg(case when month(datedonnees) =  2 then temperature end) feb,
    avg(case when month(datedonnees) =  3 then temperature end) mar,
    ...
    avg(case when month(datedonnees) = 12 then temperature end) dec
from meteo
where datedonnees >= '20200101' and datedonnees < '20210101'
group by city