现有salary表(员工ID,部门,薪水 ),请输出每个部门薪水中位数及对应的员工ID,输出字段员工ID,部门,中位数薪水。如果一个部门有偶数个员工,则输出中间两个员工ID和薪水。如果有两个员工薪水相同都可作为中位数,则随机取一位,不得两个都输出。请根据员工ID进行排序。(不得直接通过指定特定id得到预期结果)。
drop table if EXISTS employee;
create table employee
(
Id int primary key auto_increment,
Company char,
Salary DECIMAL
);
insert into employee
values (1, 'A', 2341);
insert into employee
values (null, 'A', 341);
insert into employee
values (null, 'A', 15);
insert into employee
values (null, 'A', 15314);
insert into employee
values (null, 'A', 451);
insert into employee
values (null, 'A', 513);
insert into employee
values (null, 'B', 15);
insert into employee
values (null, 'B', 13);
insert into employee
values (null, 'B', 1154);
insert into employee
values (null, 'B', 1345);
insert into employee
values (null, 'B', 1221);
insert into employee
values (null, 'B', 234);
insert into employee
values (null, 'C', 2345);
insert into employee
values (null, 'C', 2645);
insert into employee
values (null, 'C', 2645);
insert into employee
values (null, 'C', 2652);
insert into employee
values (null, 'C', 65);
insert into employee
values (null, 'D', 2345);
insert into employee
values (null, 'D', 2645);
insert into employee
values (null, 'D', 2646);
insert into employee
values (null, 'D', 2652);
insert into employee
values (null, 'D', 65);
select Id, Company, Salary
from (
select *,
ROW_NUMBER() OVER (PARTITION BY Company order BY Salary asc,Company ASC) r1,
ROW_NUMBER() OVER (PARTITION BY Company order BY Salary desc,Company ASC) r2
from employee
) as a
where r1 between r2 - 1 and r2 + 1
group by Company,Salary
order by id asc;