Mysql刷题 day07
LC 1907 按分类统计薪水
知识点:
1.select + 字面量可以直接返回该字面量。平时都是从表中取数据 ,针对这个点还真不太熟悉。
比如 select 'Low Salary' as Salary 相当于直接返回 'Low Salary'这个字符串 , 并给这个字段取名叫salary。
2.本体思路就是把各个类别的数据集都选出来 , 在union一下。
select 'Low Salary' as category , count(case when income < 20000 then 1 end) as accounts_count from Accounts
union all
select 'Average Salary' as category , count(case when income >=20000 and income <= 50000 then 1 end) as accounts_count from Accounts
union all
select 'High Salary' as category , count(case when income > 50000 then 1 end) as accounts_count from Accounts
LC 1164 指定日期的产品价格
思路
0.先把每个产品的id单独选出来
1.找到每个产品在'2019-08-16' 前的最后一次变更日期
这两步可以用公共表达式先选出来。
关于多个CTE的语法:
WITHtemp AS (...),temp2 AS (...)
SELECT ...
with temp as(
select product_id , max(change_date) as latest from Products where change_date <= '2019-08-16' group by product_id
)
,
distinct_id as(select distinct product_id from Products
)
2.关联所有产品id和对应的最后变化时间 ,第一次left join
3.选出价格 ,并且早于8-16的设置为默认值 , 第二次left join
因此,本体代码如下:
with temp as(
select product_id , max(change_date) as latest from Products where change_date <= '2019-08-16' group by product_id
)
,
distinct_id as(select distinct product_id from Products
)
select distinct_id.product_id ,
case
when new_price is not null then new_price else 10
end as price
from distinct_id left join temp on distinct_id.product_id = temp.product_id
left join Products p on p.product_id = temp.product_id and temp.latest = p.change_date
LC 626 换座位
知识点:关联子查询
何为关联子查询?
关联子查询(Correlated Subquery)是指 子查询依赖于外层查询的字段值,执行流程为:
- 外层查询逐行扫描:每次取一行数据。
- 子查询动态执行:根据外层查询的当前行值,返回相关结果。
- 结果合并:将子查询结果与外层查询的行合并。
语法:
SELECT 外层查询字段,(SELECT 子查询字段 FROM 子查询表 WHERE 子查询表.字段 = 外层表别名.字段 -- 🟢 关联条件) AS 别名
FROM 外层表 AS 外层表别名 -- 🟢 外层查询别名
WHERE 外层查询条件;
注意 ,关联子查询时 , 外层表必须取别名!
本体代码:
select
s.id ,
case
when s.id % 2 = 1 and s.id != (select count(1) from Seat) then (select student from Seat where id = s.id + 1)
when s.id % 2 = 1 and s.id = (select count(1) from Seat) then student
when s.id % 2 = 0 then (select student from Seat where id = s.id - 1)
end as student
from Seat s
其中的
(select student from Seat where id = s.id + 1)
when s.id % 2 = 0 then (select student from Seat where id = s.id - 1)
就是关联子查询。id = s.id - 1就是关联条件
具体执行流程如下:
1.外层先执行
2.没执行一行 , 就会触发子查询。
比如上面 ,当外层查到s.id = 1时,正好满足第一个case ,进入内层子查询,内层子查询是在Seat表(注意没起别名!)中查 ,id = s.id + 1 = 1 + 1. 即查到了第二行的名字,通过这样的逻辑完成交换。