每周一练(7)

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

+———+——————+——————+
| Id(INT) | RecordDate(DATE) | Temperature(INT) |
+———+——————+——————+
| 1 | 2015-01-01 | 10 |
| 2 | 2015-01-02 | 25 |
| 3 | 2015-01-03 | 20 |
| 4 | 2015-01-04 | 30 |
+———+——————+——————+

例如,根据上述给定的 Weather 表格,返回如下 Id:

+—-+
| Id |
+—-+
| 2 |
| 4 |
+—-+

 

SELECT w2.Id 
FROM Weather w1 , Weather w2
where w1.RecordDate + 1 = w2.RecordDate
and w1.Temperature < w2.Temperature

 

错误,直接+1 肯定不行的,需要使用DATEDIFF 函数

SELECT w2.Id 
FROM Weather w1 , Weather w2
where DATEDIFF(w1.RecordDate,w2.RecordDate) = -1
and w1.Temperature < w2.Temperature;

 

DATEDIFF 函数,可以计算日期差

DATEDIFF('2019-12-31','2019-12-30'); # 1
DATEDIFF('2019-12-30','2019-12-31'); # -1

 

 

 

 

 

 

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部