SQL269. 考试分数(四)
描述
牛客每次考试完,都会有一个成绩表(grade),如下:
id | job | score |
1 | C++ | 11001 |
2 | C++ | 11000 |
3 | C++ | 9000 |
4 | JAVA | 12000 |
5 | JAVA | 13000 |
6 | B | 12000 |
7 | B | 11000 |
8 | B | 9999 |
第1行表示用户id为1的用户选择了C++岗位并且考了11001分
。。。
第8行表示用户id为8的用户选择了B语言岗位并且考了9999分
请你写一个sql语句查询各个岗位分数升序排列之后的中位数位置的范围,并且按job升序排序,结果如下:
job | start | end |
B | 2 | 2 |
C++ | 2 | 2 |
Java | 1 | 2 |
解释:
第1行表示C++岗位的中位数位置范围为[2,2],也就是2。因为C++岗位总共3个人,是奇数,所以中位数位置为2是正确的(即位置为2的10000是中位数)
第2行表示Java岗位的中位数位置范围为[1,2]。因为Java岗位总共2个人,是偶数,所以要知道中位数,需要知道2个位置的数字,而因为只有2个人,所以中位数位置为[1,2]是正确的(即需要知道位置为1的12000与位置为2的13000才能计算出中位数为12500)
第3行表示前端岗位的中位数位置范围为[2,2],也就是2。因为B语言岗位总共3个人,是奇数,所以中位数位置为2是正确的(即位置为2的11000是中位数)
(注意: sqlite 1/2得到的不是0.5,得到的是0,只有1*1.0/2才会得到0.5,sqlite四舍五入的函数为round,sqlite不支持floor函数,支持cast(x as integer) 函数,不支持if函数,支持case when ...then ...else ..end函数)
示例1
输入:
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);
输出:
B|2|2 C++|2|2 Java|1|2
Sqlite 解法, 执行用时: 10ms, 内存消耗: 3448KB, 提交时间: 2021-11-22
select job, (cast(((count(job)+1)*1.0/2) as int) - (((count(job)+1)*1.0/2) < (cast(((count(job)+1)*1.0/2) as int)))) as start, (cast(((count(job)+1)*1.0/2) as int) + (((count(job)+1)*1.0/2) > (cast(((count(job)+1)*1.0/2) as int)))) as end from grade group by job order by job
Sqlite 解法, 执行用时: 10ms, 内存消耗: 3456KB, 提交时间: 2021-09-06
select job, case when total%2 = 0 then total/2 else (total+1)/2 end as start, case when total%2 = 0 then total/2 + 1 else (total + 1)/2 end as end from (select job, count(*) total from grade group by job)
Sqlite 解法, 执行用时: 10ms, 内存消耗: 3460KB, 提交时间: 2021-08-31
select job , (case when count(*)%2=0 then count(*)/2 else (count(*)+1)/2 end) as start, (case when count(*)%2=0 then (count(*)/2+1) else (count(*)+1)/2 end) as end from grade group by job order by job ,score desc
Sqlite 解法, 执行用时: 10ms, 内存消耗: 3500KB, 提交时间: 2021-11-30
select job, case when num%2=1 then (num+1)/2 else num/2 end as start, case when num%2=0 then num/2+1 else (num+1)/2 end as end from (select job,count(id) num from grade group by job) t order by job;
Sqlite 解法, 执行用时: 11ms, 内存消耗: 3296KB, 提交时间: 2020-11-01
SELECT job, CASE WHEN total%2=0 THEN total/2 ELSE (total+1)/2 END AS `start`, CASE WHEN total%2=0 THEN total/2+1 ELSE (total+1)/2 END AS `end` FROM (SELECT job,COUNT(1) AS total FROM grade GROUP BY job)t;