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