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) | RecordDate(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 | +----+
解题思路:
自己连接自己,条件是连接自己昨天的行。
TO_DAYS函数 返回一个天数! 啊哈?什么天数? 从年份0开始的天数
比如:
mysql> SELECT TO_DAYS(‘1997-10-07′);
结果 729669
就是从0年开始 到1997年10月7号之间的天数
理解这个之后那么一切就变得拉么简单!有一张表!lito表 有一个字段 create_time 类型 datetime
如果要查询当前表中昨天的数据那么
select * from lito where to_days(now())-to_days(create_time)<1
select w.Id from Weather as w
join Weather as preW on TO_DAYS(w.RecordDate)=1+TO_DAYS(preW.RecordDate)
where w.Temperature > preW.Temperature;