如何基于weather表统计2019年各月降雪天数?SQL查询问题
问题描述
我有一张名为weather的表,结构及示例数据如下:
snowfall dayoftheyear observationdate 0.1 28 2019-01-28 1.9 67 2019-03-08 0.13 316 2019-11-12
该表共有137行数据,日期范围至2019-12-31。我的需求是统计2019年每个月的降雪天数(即当月snowfall>0的observationdate记录数)。
我尝试了以下SQL语句:
select sum(snowfall ) precipitation, right(observation_date, 7) EachMonth from weather where observation_date between '2019-01-01' and '2019-12-31' and city = 'Olympia' and snowfall > 0 group by EachMonth order by EachMonth
但得到的是各月降雪量总和,而非降雪天数。期望得到如下格式的结果:
TotalDaysofSnowfall EachMonth 4 01 7 08
请问如何实现该需求?
解决方案
要统计降雪天数,核心是用count()函数替代原SQL中的sum(snowfall),因为我们需要的是满足条件的记录行数,而非降雪量总和。同时根据期望结果调整月份的提取方式,具体如下:
方案1:使用日期函数提取月份
如果你的SQL方言支持month()函数(如MySQL、PostgreSQL、SQL Server等),可以直接提取月份:
select count(*) as TotalDaysofSnowfall, lpad(month(observationdate), 2, '0') as EachMonth from weather where observationdate between '2019-01-01' and '2019-12-31' and city = 'Olympia' and snowfall > 0 group by month(observationdate) order by EachMonth
count(*):统计每组内符合条件的记录数,即当月降雪天数;lpad(month(...), 2, '0'):将月份数字补前导零,确保返回01、08这类两位格式(若不需要补零,直接用month(observationdate)即可)。
方案2:使用字符串截取提取月份
如果不支持month()函数,可通过字符串截取获取月份部分:
select count(*) as TotalDaysofSnowfall, substring(observationdate, 6, 2) as EachMonth from weather where observationdate between '2019-01-01' and '2019-12-31' and city = 'Olympia' and snowfall > 0 group by substring(observationdate, 6, 2) order by EachMonth
substring(observationdate, 6, 2):从2019-01-28这类日期字符串的第6位开始截取2个字符,得到01格式的月份。
补充说明
原SQL中right(observation_date,7)返回的是2019-01格式的年月,调整后可以得到你期望的仅两位月份的结果;另外where条件中已经过滤了snowfall>0的记录,所以count(*)直接统计的就是降雪天数。
内容的提问来源于stack exchange,提问作者user18572659
相关产品推荐
相关产品推荐

