赞
踩
请编写SQL查询来查找每个公司的薪水中位数。
挑战点:你是否可以在不使用任何内置的SQL函数的情况下解决此问题。
-----+------------+--------+ |Id | Company | Salary | +-----+------------+--------+ |1 | A | 2341 | |2 | A | 341 | |3 | A | 15 | |4 | A | 15314 | |5 | A | 451 | |6 | A | 513 | |7 | B | 15 | |8 | B | 13 | |9 | B | 1154 | |10 | B | 1345 | |11 | B | 1221 | |12 | B | 234 | |13 | C | 2345 | |14 | C | 2645 | |15 | C | 2645 | |16 | C | 2652 | |17 | C | 65 | +-----+------------+--------+
中位数理解:
窗口函数排序后,再where筛选
SELECT id, company, round(avg(salary),0) as 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 -- 各公司的薪水记录数
) a
WHERE row_num IN (FLOOR((count_id + 1)/2), FLOOR((count_id + 2)/2))
GROUP BY id, company
#输出结果
+-----+------------+--------+
|Id | Company | Salary |
+-----+------------+--------+
|5 | A | 451 |
|6 | A | 513 |
|12 | B | 234 |
|9 | B | 1154 |
|14 | C | 2645 |
+-----+------------+--------+
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/median-employee-salary
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。