题目描述:sql语句查询各个岗位分数升序排列之后的中位数位置的范围,并且按job升序排序。
个人思路:没什么好讲的,首先找出各岗位对应总报考数。总数为偶的情况,中位数为中间的两个。总数为奇的情况,中位数就是中间那个。
注意:不要跟python搞混了,mysql里是没有//这种运算符的!!

代码:
最直接的写法:

select job ,
       floor((sum(1)+1)/2) as start,
       floor((sum(1)+2)/2) as end
from grade
group by job
order by job

FLOOR(x) 返回小于或等于 x 的最大整数.
sum(1)跟count(*)是一个意思都是对获取总行数的意思。因为这里我们按照job进行分组,所以获取的每个job的总行数。

case..when..then..else写法 :

with t1 as
(
    select job, count(score) as num
    from grade
    group by job
)

select job,
    (case when num%2=0 then ceil(num/2) else ceil(num/2) end)as start,
    (case when num%2=0 then ceil(num/2+1) else ceil(num/2) end) as end
from t1
order by job

CEIL(x) 返回大于或等于 x 的最小整数.

if函数:

with t1 as
(
    select job, count(score) as num
    from grade
    group by job
)

select job,
    if(num%2=0, ceil(num/2), ceil(num/2))as start,
    if(num%2=0, ceil(num/2+1), ceil(num/2)) as end
from t1
order by job

IF(expr,v1,v2) 如果表达式 expr 成立,返回结果 v1;否则,返回结果 v2。