Question:
Employee 表包含所有員工。Employee 表有三列:員工Id,公司名和薪水。

image.png
編寫SQL查詢來查找每個公司的薪水中位數(shù)。挑戰(zhàn)點:你是否可以在不使用任何內(nèi)置的SQL函數(shù)的情況下解決此問題。

image.png
思路:
1、按照company進行分組排序—中位數(shù)在每組數(shù)據(jù)里面的靠中間排序的地方
2、計算每組里面的數(shù)據(jù)總數(shù)—每組的中間位置,和各組數(shù)據(jù)總數(shù)有關(guān)
3、限定每組company中的中位數(shù)所在位置—位置在num/2~num/2+1
查詢出表a:利用變量@求得的分組排序
查詢出表b:每個company的總數(shù)
表a join 表b:在一個表里獲得排序和各組總數(shù)
where:條件限定,選出ranking在每組數(shù)據(jù)中的正確位置
select t.id,t.company,t.salary
from
(select a.id,a.company,a.salary,a.ranking,b.num
from
(select id,company,salary,
if(@pre_company=company,@cur_rank:=@cur_rank+1,@cur_rank:=1) ranking,
@pre_company:=company
from
employee3,(select @pre_company:=null,@cur_rank:=1) r
order by company,salary) a
join
(select company,count(*) num from employee3 group by company) b
on a.company=b.company
) t
where t.ranking between t.num/2 and t.num/2+1