如何在 SQL Server 中调整每月温度?
Posted
技术标签:
【中文标题】如何在 SQL Server 中调整每月温度?【英文标题】:How to pivot temperature per month in SQL Server? 【发布时间】:2020-10-09 12:35:44 【问题描述】:我可以这样算出每年的平均温度:
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'."
错误。
这是我希望看到的结果:
【问题讨论】:
请以表格文本形式向我们展示您想要的结果。 【参考方案1】: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;
【讨论】:
【参考方案2】:我会推荐条件聚合:
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()
稍微缩短语法,但它可能比半开区间效率低:
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
【讨论】:
以上是关于如何在 SQL Server 中调整每月温度?的主要内容,如果未能解决你的问题,请参考以下文章
仅当每月少于 10 天是 NA 时,如何使用 dplyr 和 lubridate 每月汇总每日数据?