当前位置: 代码迷 >> 综合 >> 197. Rising Temperature - 上升的温度 <easy>
  详细解决方案

197. Rising Temperature - 上升的温度 <easy>

热度:42   发布时间:2024-03-07 06:11:42.0

表 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          |
+----+------------+-------------+

Result table:
+----+
| id |
+----+
| 2  |
| 4  |
+----+
2015-01-02 的温度比前一天高(10 -> 25)
2015-01-04 的温度比前一天高(30 -> 20)

Write an SQL query to find all dates' id with higher temperature compared to its previous dates (yesterday). Return the result table in any order.

分析:相邻两天日期的比较,Mysql内置函数中考虑使用:

1、DATE_SUB(date,INTERVAL expr type) ; 

2、DATEDIFF(date1,date2);

# DATEDIFF(b.recordDate,a.recordDate)=1 返回两个日期间隔的天数
# DATE_SUB(b.recordDate,INTERVAL 1 DAY) 返回两个日期间隔的天数
select b.id 
from Weather a,Weather b
where a.recordDate = DATE_SUB(b.recordDate,INTERVAL 1 DAY) and b.Temperature > a.Temperature
#where DATEDIFF(b.recordDate,a.recordDate)=1 and b.Temperature > a.Temperature

 

 

  相关解决方案