197. Rising Temperature

第一道关于sql语言的题目

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

解答:

因为太久没写过sql了,解答方式是看了fabrizio3的答案

SELECT wt1.Id 
FROM Weather wt1, Weather wt2
WHERE wt1.Temperature > wt2.Temperature AND 
      TO_DAYS(wt1.DATE)-TO_DAYS(wt2.DATE)=1;//TO_DAYS把日期转换为从0到该日期的天数,从而判断w1是否w2的后一天
hsldymq的答案
(MYSQL)
SELECT a.Id FROM Weather AS a, Weather AS b
WHERE DATEDIFF(a.Date, b.Date)=1 AND a.Temperature > b.Temperature//唯一区别是用了DATEDIFF方法,该方法在oracle中没有,在MS SQL SERVER中该函数用法不同



猜你喜欢

转载自blog.csdn.net/weixin_39525565/article/details/80286288