rising-temperature --leetcode

https://leetcode.com/problems/rising-temperature/description/
Given a Weather table, write a SQL query to find all dates' Ids
with higher temperature compared to its previous (yesterday's) dates.

+---------+------------+------------------+
| Id(INT) | Date(DATE) | Temperature(INT) |
+---------+------------+------------------+
|       1 | 2015-01-01 |               10 |
|       2 | 2015-01-02 |               25 |
|       3 | 2015-01-03 |               20 |
|       4 | 2015-01-04 |               30 |
+---------+------------+------------------+
For example, return the following Ids for the above Weather table:
+----+
| Id |
+----+
|  2 |
|  4 |
+----+

solution:

select w.Id from Weather w
where w.Temperature > (select w2.Temperature from Weather w2 where w2.Date = date_add(w.Date, interval -1 day))

能夠這麼查的  通常能夠關聯 固然mysql還有不少其餘的日期函數 DATEDIFF TO_DAYS
select w.Id from Weather w
inner join Weather w2 on w.Date = date_add(w2.Date, interval 1 day)
where w.Temperature >  w2.Temperature

SELECT w1.Id FROM Weather w1, Weather w2
WHERE w1.Temperature > w2.Temperature AND DATEDIFF(w1.Date, w2.Date) = 1;

git地址:https://github.com/woshiyexinjie/leetcode-xinmysql

相關文章
相關標籤/搜索