前言
练习sql语句,所有题目来自于力扣(https://leetcode.cn/problemset/database/)的免费数据库练习题。
今日题目:
1294.不同国家的天气类型
表:Countries
列名 | 类型 |
---|---|
country_id | int |
country_name | varchar |
country_id 是这张表的主键(具有唯一值的列)。
该表的每行有 country_id 和 country_name 两列。
列名 | 类型 |
---|---|
country_id | int |
weather_state | varchar |
day | date |
(country_id, day) 是该表的复合主键(具有唯一值的列)。
该表的每一行记录了某个国家某一天的天气情况。
编写解决方案找到表中每个国家在 2019 年 11 月的天气类型。
天气类型的定义如下:
当 weather_state 的平均值小于或等于 15 返回 Cold,
当 weather_state 的平均值大于或等于 25 返回 Hot,
否则返回 Warm。
以 任意顺序 返回你的查询结果。
- 首先梳理表内容,题干一共给了两张表,一张国家表,记录了国家id,国家名,一张天气表,记录了国家id,天气状态,以及日期。
- 其次分析需求,需要找到每个国家在2019年11月的天气类型当 weather_state 的平均值小于或等于 15 返回 Cold,当 weather_state 的平均值大于或等于 25 返回 Hot,否则返回 Warm。
- 那么首先肯定要筛选所有2019年11月的日期
- 然后将两张表连接起来,将天气表作为主表
- 最后对国家id进行分组,对其天气状态求平均值,通过case when逻辑判断得到最终结果
select country_name,
case
when avg(weather_state) <= 15 then "Cold"
when avg(weather_state) >= 25 then "Hot"
else "Warm"
end as weather_type
from Weather w
left join Countries c
on w.country_id = c.country_id
where substr(day,1,7) = "2019-11"
group by w.country_id
结果:
总结:
能运行就行。