mysql每日一题0718----- 每个公司的工资的中位数
hope you can learn and enjoy 😄
最近关注了一个公众号,该公众号主要围绕着数据库为技术主线展开,里面有每日一题
- T0716 表包含所有员工,其中有三列:员工 Id,公司名和薪水。
ID | Company | Salary |
---|---|---|
1 | A | 8341 |
2 | A | 9410 |
3 | A | 10050 |
4 | A | 15314 |
5 | A | 8451 |
6 | A | 9513 |
7 | B | 10005 |
8 | B | 13000 |
9 | B | 11540 |
10 | B | 10345 |
11 | B | 12210 |
12 | B | 9234 |
13 | C | 12000 |
14 | C | 8900 |
15 | C | 9000 |
16 | C | 10100 |
17 | C | 8000 |
- 现在 的需求是求每个公司的工资的中位数
需求结果如下:
ID | Company | Salary |
---|---|---|
6 | A | 9513 |
2 | A | 9410 |
9 | B | 11540 |
10 | B | 10345 |
15 | C | 9000 |
代码实现:
CREATE TABLE T0716
(
ID INT,
Company VARCHAR(10),
Salary INT
);
INSERT INTO T0716 VALUES
(1,'A',8341),
(2,'A',9410),
(3,'A',10050),
(4,'A',15314),
(5,'A',8451),
(6,'A',9513),
(7,'B',10005),
(8,'B',13000),
(9,'B',11540),
(10,'B',10345),
(11,'B',12210),
(12,'B',9234),
(13,'C',12000),
(14,'C',8900),
(15,'C',9000),
(16,'C',10100),
(17,'C',8000)
查询语句如下:
- 创建临时表
- 根据中位数的条件判断筛选出合适的记录
WITH temp AS (
SELECT a.*,ROW_NUMBER() over (PARTITION BY company ORDER BY Salary DESC) paiming,count(1) over (PARTITION BY company) num FROM t0716 a)
SELECT a.ID,a.Company,a.Salary FROM temp a WHERE paiming=round(num/2,0) OR (paiming=round(num/2)+1 AND num % 2=0)