力扣197(MySQL)-上升的温度(简单)

题目:

表: Weather

编写一个 SQL 查询,来查找与之前(昨天的)日期相比温度更高的所有日期的 id 。

返回结果 不要求顺序 。

查询结果格式如下例。

 解题思路:

方法一:使用窗口函数lag() over( partition by 分组列 order by 排序列) 和 datediff(startdate,endstart)

①先将recordDate和Temperature列向下移动一行,并将日期进行升序排序。

1 SELECT id, recordDate, Temperature, 
2     lag(recordDate, 1) over(order by recordDate) AS beforeDate,
3     lag(Temperature,1) over(ORDER BY recordDate ) AS beforeTemperature
4 FROM weather 

 ②然后再用第一步查找出来的结果作为临时表,来筛选出两个连续日期(差值为1)和后一天温度比前一天高的id。

1 SELECT id
2 FROM
3     ( SELECT id, recordDate, Temperature, 
4     lag(recordDate, 1) over(order by recordDate) AS beforeDate,
5     lag(Temperature,1) over(ORDER BY recordDate ) AS beforeTemperature
6     FROM weather ) as a
7 where Temperature > beforeTemperature and datediff( recordDate,beforeDate) = 1;    

 方法二:笛卡尔积:假设集合A={a, b},集合B={0, 1, 2},则两个集合的笛卡尔积为{(a, 0), (a, 1), (a, 2), (b, 0), (b, 1), (b, 2)}。

将weather表进行自连接,分别将别名设置为w1,w2,连接条件是:w2的日期与w1的日期差1 且 w2的温度比w1的温度大。

1 select w2.id
2 from Weather w1
3 join Weather w2
4 where datediff(w2.recordDate, w1.recordDate) = 1 
5 and w2.Temperature > w1.Temperature;

小知识:

①lag()和head()【图片来源

lag():我理解为向下移动x行

 head():我理解为向上移动x行

 ②detediff(datepart,startdate.endddate):返回enddate-startdate的值。

1 select datediff(year,'2018-07-13','2018-07-14');--output:1
2 select datediff(year,'2018-07-14','2018-07-13');--output:-1

③LEFT JOIN 和RIGHT JOIN需要用ON,INNER JOIN可以用WHERE,INNER JOIN可以省略不写,直接用逗号隔开两个表。

posted on 2023-03-17 13:46  我不想一直当菜鸟  阅读(98)  评论(0编辑  收藏  举报