高频SQL50题 第九天 | 1164. 指定日期的产品价格、1204. 最后一个能进入巴士的人、1907. 按分类统计薪水
1164. 指定日期的产品价格
题目链接:https://leetcode.cn/problems/product-price-at-a-given-date/description/?envType=study-plan-v2&envId=sql-free-50
状态:已完成
考点:
- group by + select语句中使用聚合函数max():获取每个产品的最新日期
- 子查询:获取2019-08-16之前每个产品的最新价格
- 连接:针对未在2019-08-16之前更新价格的产品,通过连接操作产生的空值,结合ifnull()函数转化为默认值
select T1.product_id, ifnull(new_price, 10) as price
from (select distinct product_idfrom Products
)as T1 left join (select product_id, new_pricefrom Productswhere (product_id, change_date) in (select product_id, max(change_date) as max_datefrom Productswhere datediff(change_date, "2019-08-16") <= 0group by product_id)
) as T2
on T1.product_id = T2.product_id
1204. 最后一个能进入巴士的人
题目链接:https://leetcode.cn/problems/last-person-to-fit-in-the-bus/description/?envType=study-plan-v2&envId=sql-free-50
状态:需二刷,完全没有解题思路
解题思路:首先通过连接操作获取{1,2,3,…,i}的子集,然后计算每个子集的和,筛选出所有和<1000的子集,选取其中最大的i,即为最后一个进入巴士的人
考点:
- join + on,连接操作
- group by + having,分组操作
- order by + desc + limit k,降序排序+输出Top-k操作
select Q1.person_name
from Queue as Q1 join Queue as Q2
on Q1.turn >= Q2.turn
group by Q1.turn
having sum(Q2.weight) <= 1000
order by sum(Q2.weight) desc
limit 1
1907. 按分类统计薪水
题目链接:https://leetcode.cn/problems/count-salary-categories/?envType=study-plan-v2&envId=sql-free-50
状态:已完成
考点:使用UNION横向连接表格
注:不需要手动创建临时表,直接使用UNION连接多个表格即可,MYSQL会自动创建临时表
select "Low Salary" as category, count(*) as accounts_count
from Accounts
where income < 20000
UNION
select "Average Salary" as category, count(*) as accounts_count
from Accounts
where income >= 20000 and income <= 50000
UNION
select "High Salary" as category, count(*) as accounts_count
from Accounts
where income > 50000