数据
drop table if exists grade;
CREATE TABLE grade(
`id` int(4) NOT NULL,
`job` varchar(32) NOT NULL,
`score` int(10) NOT NULL,
PRIMARY KEY (`id`));
INSERT INTO grade VALUES
(1,'C++',11001),
(2,'C++',10000),
(3,'C++',9000),
(4,'Java',12000),
(5,'Java',13000),
(6,'B',12000),
(7,'B',11000),
(8,'B',9999),
(9,'B',10002);
利用窗口函数增加三列
select *,
count(score) over(partition by job) as total,
row_number() over(partition by job order by score) as ascend,
row_number() over(partition by job order by score desc) as descend
from grade
利用这三列数求出处于中位数的数据(完整代码)
with t_rank as
(
select *,
count(score) over(partition by job) as total,
row_number() over(partition by job order by score) as ascend,
row_number() over(partition by job order by score desc) as descend
from grade
)
select id,job,score,descend
from t_rank
where ascend >= total/2 and descend >= total/2
order by id
牛客原题
https://www.nowcoder.com/practice/b626ff9e2ad04789954c2132c74c0512?tpId=82&&tqId=35496&rp=1&ru=/ta/sql&qru=/ta/sql/question-ranking