SQL练习20201224

197.上升的温度

表 Weather

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| recordDate    | date    |
| temperature   | int     |
+---------------+---------+

id是这个表的主键
该表包含特定日期的温度信息

编写一个SQL查询,来查找与之前(昨天的)日期相比温度更高的所有日期的id。返回结果不要求顺序

查询结果格式如下:

Weather
+----+------------+-------------+
| id | recordDate | Temperature |
+----+------------+-------------+
| 1  | 2015-01-01 | 10          |
| 2  | 2015-01-02 | 25          |
| 3  | 2015-01-03 | 20          |
| 4  | 2015-01-04 | 30          |
+----+------------+-------------+

Result table:
+----+
| id |
+----+
| 2  |
| 4  |
+----+
2015-01-02 的温度比前一天高(10 -> 25)
2015-01-04 的温度比前一天高(20 -> 30)

解决方法1,窗口函数:

​ datediff函数,datediff(date1,date2) 作用是两个日期相减,返回date1-date2的天数。

select a.id as id
from(
select id,recordDate,Temperature,
lag(recordDate,1) over(order by recordDate) as lastday
,lag(Temperature,1) over(order by recordDate) as lastTemper
from Weather ) a
where a.Temperature>a.lastTemper and datediff(a.recordDate,lastday)=1

解决方法2,左连接+date_sub函数

select w1.id
from Weather w1 
left join Weather w2 on  date_sub(w1.recordDate, interval 1 day) = w2.recordDate 
where w1.Temperature > w2.Temperature
posted @ 2020-12-24 22:46  有心有梦  阅读(99)  评论(0编辑  收藏  举报