码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode:Rising Temperature

时间:2015-07-04 18:22:08      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

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 |
+----+
分析:意思就是在Weather表中,写一个SQL查询与前一天相比温度更高的日期对应的ID。
代码:
# Write your MySQL query statement below
SELECT w1.Id 
FROM Weather w1 JOIN Weather w2 ON TO_DAYS(w1.Date)=TO_DAYS(w2.Date)+1 And w1.Temperature>w2.Temperature; 

 其中,TO_DAYS(date) 给定一个日期date, 返回一个天数 (从年份0开始的天数 ) 

其他解法:

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

  其中,dateDiff() 函数返回两个日期之间的天数。

还有这样的方式:

 date_add(w1.date,interval 1 day)=w2.date

w2.Date = DATE_SUB(w1.Date, INTERVAL 1 DAY)

leetcode:Rising Temperature

标签:

原文地址:http://www.cnblogs.com/carsonzhu/p/4620943.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!