(LeetCode 569) 员工薪水中位数

Employee 表包含所有员工。Employee 表有三列:员工Id,公司名和薪水。

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

请编写SQL查询来查找每个公司的薪水中位数。

挑战点:你是否可以在不使用任何内置的SQL函数的情况下解决此问题。

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

解题思路

  1. 不同部门薪水排序 rank
  2. 不同部门人数
  3. 通过人数计算出中位数,总数奇数 7 :中位数 4 ,总数偶数 6 :中位数 3、4
    rank >= total/2 and rank <= total/2 + 1 ;

1. 不同部门薪水排序 rank

SELECT
    a.*,
    IF( @p = company, @r := @r + 1, @r := 1 ) AS rank,
    @p := company 
FROM
    employee a,
    ( SELECT @p := 0, @r := 0 ) r 
ORDER BY
    company,
    salary DESC;

2. 不同部门人数

select company,count(1) as total from employee group by company;

3. 通过人数计算出中位数,总数奇数 7 :中位数 4 ,总数偶数 6 :中位数 3、4

select a.id,a.company,a.salary from 
    (SELECT
    a.*,
    IF( @p = company, @r := @r + 1, @r := 1 ) AS rank,
    @p := company 
FROM
    employee a,
    ( SELECT @p := 0, @r := 0 ) r 
ORDER BY
    company,
    salary DESC) a
inner join 
(select company,count(1) as total from employee group by company) b
on a.company = b.company and a.rank >= b.total/2 and a.rank <= b.total/2 + 1;

你可能感兴趣的:((LeetCode 569) 员工薪水中位数)