SQL 每日一题(6)
继续做题!
原始表:employee_resignations表
employee_id | resignation_date |
---|---|
1001 | 2022-03-15 |
1002 | 2022-11-20 |
1003 | 2023-01-05 |
1004 | 2023-07-12 |
1005 | 2024-02-28 |
第一题:
查询累计到每个年度的离职人数
结果输出:年度、当年离职人数、累计离职人数
第二题:
第一次累计超过 100 人离职的是哪一年?对应的当年离职人数为多少?
填写示例:2008 120
第一题思路:累积离职利用sum窗口函数求和即可,当年离职利用order by排序即可
SELECTYEAR(resignation_date) AS year,COUNT(*) AS current_year_resignations,SUM(COUNT(*)) OVER (ORDER BY YEAR(resignation_date)) AS cumulative_resignations
FROM employee_resignations
GROUP BY YEAR(resignation_date)
ORDER BY YEAR(resignation_date);
第二题思路,将第一题转换为t1表,在t1表基础上进行查询即可
WITH t1 AS (SELECT YEAR(resignation_date) AS year,COUNT(*) AS current_year_resignations,SUM(COUNT(*)) OVER (ORDER BY YEAR(resignation_date)) AS cumulative_resignationsFROM employee_resignationsGROUP BY YEAR(resignation_date)
)
SELECT year,current_year_resignations
FROM t1
WHERE cumulative_resignations >= 100
ORDER BY cumulative_resignations DESC
LIMIT 1;