D8-leetcode197. 上升的温度(简单)
2020-07-02 本文已影响0人
喝奶茶不加奶茶
给定一个 Weather 表,编写一个 SQL 查询,来查找与之前(昨天的)日期相比温度更高的所有日期的 Id。

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

准备数据:
Create table If Not Exists Weather (Id int, RecordDate date, Temperature int);
insert into Weather (Id, RecordDate, Temperature) values ('1', '2015-01-01', '10');
insert into Weather (Id, RecordDate, Temperature) values ('2', '2015-01-02', '25');
insert into Weather (Id, RecordDate, Temperature) values ('3', '2015-01-03', '20');
insert into Weather (Id, RecordDate, Temperature) values ('4', '2015-01-04', '30');
解决思路:
select * from Weather a
inner join Weather b
on a.Temperature>b.Temperature
where datediff(a.RecordDate,b.RecordDate)=1;

select a.Id from Weather a
inner join Weather b
on a.Temperature>b.Temperature
where datediff(a.RecordDate,b.RecordDate)=1;

知识点:
两个日期计算天数差
date_diff(time1,time2):返回两个日期之间(time1-time2)的天数。
eg:
select datediff('2008-08-08','2008-08-01');-- 相差:7 天