今天在力扣看到一个sql题,比较有意思,分享一下。
原题目:197. 上升的温度
现有表:weather
column name | type |
---|---|
id | int |
recordDate | date |
temperature | int |
id 是该表具有唯一值的列。
没有具有相同 recordDate 的不同行。
该表包含特定日期的温度信息。
问题:编写解决方案,找出与之前(昨天的)日期相比温度更高的所有日期的 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 |
解题思路:
1. 先把表与自身进行关联,这样就可以进行横向的比较
2. 此时需要一个日期比较函数datediff()来找出相差一天的日期
代码:
select a.id as id from weather a join weather b where datediff(a.recordDate,b.recordDate)=1 and a.temperature>b.temperature;