标签:
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)
标签:
原文地址:http://www.cnblogs.com/carsonzhu/p/4620943.html