LeetCode(数据库)- 员工薪水中位数
Posted Lux_Sun
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode(数据库)- 员工薪水中位数相关的知识,希望对你有一定的参考价值。
题目链接:点击打开链接
题目大意:略。
解题思路:解决方案(2):对于一个奇数 / 偶数长度数组中的中位数,大于这个数的数值个数等于小于这个数的数值个数。最后需要“GROUP BY Company, Salary”是因为子连接时会有左右重复的情况。
AC 代码
-- 解决方案(1)
SELECT id, company, salary
FROM
(
SELECT id, company, salary,
ROW_NUMBER() OVER (PARTITION BY company ORDER BY Salary ASC, id ASC) AS row_num,
COUNT(Id) OVER (PARTITION BY company) AS count_id
FROM Employee
)
WHERE row_num IN (FLOOR((count_id + 1)/2), FLOOR((count_id + 2)/2));
-- 解决方案(2)
SELECT Id, Company, Salary
FROM Employee
WHERE Id in (
SELECT e1.Id
FROM Employee e1
JOIN Employee e2
ON e1.Company = e2.Company
GROUP BY e1.Id
HAVING SUM(CASE WHEN e1.Salary >= e2.Salary THEN 1 ELSE 0 END) >= COUNT(*)/2
AND SUM(CASE WHEN e1.Salary <= e2.Salary THEN 1 ELSE 0 END) >= COUNT(*)/2
)
GROUP BY Company, Salary
ORDER BY Company;
以上是关于LeetCode(数据库)- 员工薪水中位数的主要内容,如果未能解决你的问题,请参考以下文章