力扣-上升的温度

大家好,我是空空star,本篇带大家了解一道简单的力扣sql练习题。


前言


一、题目: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          |
+----+------------+-------------+
输出:
+----+
| id |
+----+
| 2  |
| 4  |
+----+

解释:
2015-01-02 的温度比前一天高(10 -> 25)
2015-01-04 的温度比前一天高(20 -> 30)

二、解题

1.正确示范①

提交SQL

select u2.id from Weather u1
left join Weather u2 
on DATE_ADD(u1.recordDate,INTERVAL 1 DAY)=u2.recordDate
where u2.Temperature>u1.Temperature;

运行结果

2.正确示范②

提交SQL

select u2.id from Weather u1,Weather u2 
where DATE_SUB(u2.recordDate,INTERVAL 1 DAY)=u1.recordDate
and u2.Temperature>u1.Temperature;

运行结果

3.正确示范③

提交SQL

select id from Weather u1
where exists (
    select 1 from Weather u2 
    where DATE_ADD(u2.recordDate,INTERVAL 1 DAY)=u1.recordDate 
    and u1.Temperature>u2.Temperature
)

运行结果

4.正确示范④

提交SQL

select u2.id from Weather u1
join Weather u2 
on DATEDIFF(u2.recordDate,u1.recordDate)=1
where u2.Temperature>u1.Temperature;

运行结果

5.其他


总结

DATE_ADD(date,INTERVAL expr type)函数返回与date加上INTERVAL时间间隔的日期。
DATE_SUB(date,INTERVAL expr type)函数返回与date减去INTERVAL时间间隔的日期。
DATEDIFF(date1,date2) 函数计算两个日期之间相差的天数。

猜你喜欢

转载自blog.csdn.net/weixin_38093452/article/details/129740206
今日推荐