569. Median Employee Salary----通过分组排序来判断中位数

The Employee table holds all employees. The employee table has three columns: Employee Id, Company Name, and Salary.

+-----+------------+--------+
|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     |
+-----+------------+--------+

Write a SQL query to find the median salary of each company. Bonus points if you can solve it without using any built-in SQL functions.

+-----+------------+--------+
|Id   | Company    | Salary |
+-----+------------+--------+
|5    | A          | 451    |
|6    | A          | 513    |
|12   | B          | 234    |
|9    | B          | 1154   |
|14   | C          | 2645   |
+-----+------------+--------+

解题思路:通过窗口函数对每个公司的职员进行编号,并统计职员数量。如果数量couting是偶数,则ranking = (counting/2,counting/2 +1),如果是奇数,ranking = (couting+1)/2,但是counting/2,counting/2 +1,(couting+1)/2 不会同时是整数,所以直接可以可以筛选出中位数。

WITH tmp AS 
(SELECT *, 
COUNT(id) OVER (PARTITION BY company) AS counting,
ROW_NUMBER() OVER (PARTITION BY company ORDER BY salary) AS ranking
FROM employee)
SELECT id, company, salary
FROM tmp
WHERE ranking IN (counting/2, (counting+1)/2, counting/2+1);

其他解题思路见:愁!MySQL中如何查询中位数

分类排名示例:一文解决所有MySQL分类排名问题

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值