197. 上升的溫度:dateDiff
SQL架構
給定一個 Weather 表,編寫一個 SQL 查詢,來查找與之前(昨天的)日期相比溫度更高的所有日期的 Id。
+---------+------------------+------------------+
| 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 |
+---------+------------------+------------------+
例如,根據上述給定的 Weather 表格,返回如下 Id:
+----+
| Id |
+----+
| 2 |
| 4 |
+----+
思路:
- 關係:日期相鄰,且後面的溫度大於前天
- 解決辦法:使用dateDiff
- dateDiff(data_a, data_b) 返回的結果是data_a - data_b
# Write your MySQL query statement below
# select w2.Id from Weather w1, Weather w2 不用用id做判斷 不一定是升序
# where w1.Id = W2.Id-1 and W2.Temperature > w1.Temperature
select a.Id from Weather as a
join Weather as b
on a.Temperature > b.Temperature
and dateDiff(a.RecordDate,b.RecordDate) = 1
620. 有趣的電影 mod
SQL架構
某城市開了一家新的電影院,吸引了很多人過來看電影。該電影院特別注意用戶體驗,專門有個 LED顯示板做電影推薦,上面公佈着影評和相關電影描述。
作爲該電影院的信息部主管,您需要編寫一個 SQL查詢,找出所有影片描述爲非 boring (不無聊) 的並且 id 爲奇數 的影片,結果請按等級 rating 排列。
例如,下表 cinema:
+---------+-----------+--------------+-----------+
| id | movie | description | rating |
+---------+-----------+--------------+-----------+
| 1 | War | great 3D | 8.9 |
| 2 | Science | fiction | 8.5 |
| 3 | irish | boring | 6.2 |
| 4 | Ice song | Fantacy | 8.6 |
| 5 | House card| Interesting| 9.1 |
+---------+-----------+--------------+-----------+
對於上面的例子,則正確的輸出是爲:
+---------+-----------+--------------+-----------+
| id | movie | description | rating |
+---------+-----------+--------------+-----------+
| 5 | House card| Interesting| 9.1 |
| 1 | War | great 3D | 8.9 |
+---------+-----------+--------------+-----------+
思路:
- 難點在於求奇數
- 奇數的方法: id%2=1, id&1, mod(id,2)=1
# Write your MySQL query statement below
select id, movie, description, rating from
cinema
where description <> 'boring'
and id%2=1 order by rating desc
# mod(id,2)=1
# id&1
# id % 2 = 1
627. 交換工資: if; case when then end
- https://leetcode-cn.com/problems/swap-salary/
SQL架構
給定一個 salary 表,如下所示,有 m = 男性 和 f = 女性 的值。交換所有的 f 和 m 值(例如,將所有 f 值更改爲 m,反之亦然)。要求只使用一個更新(Update)語句,並且沒有中間的臨時表。
注意,您必只能寫一個 Update 語句,請不要編寫任何 Select 語句。
例如:
id | name | sex | salary |
---|---|---|---|
1 | A | m | 2500 |
2 | B | f | 1500 |
3 | C | m | 5500 |
4 | D | f | 500 |
運行你所編寫的更新語句之後,將會得到以下表:
id | name | sex | salary |
---|---|---|---|
1 | A | f | 2500 |
2 | B | m | 1500 |
3 | C | f | 5500 |
4 | D | m | 500 |
思路:
- 條件語句
- if(condition, val1, val2) 如果condition 爲true時,值爲val1,爲false時,值爲val2
- case sex when condition1 then val1 when condition2 then val2 end
# Write your MySQL query statement below
# update salary set sex = if(sex='m', 'f', 'm')
update salary set sex = case sex when 'm' then 'f' when 'f' then 'm' end