員工薪水中位數

2021-10-01 04:39:11 字數 1611 閱讀 9929

先用自定義變數分組排序,定義@num為序號,初始化為0,定義@last為上一行的部門,定義為null,

然後進行查詢,@num:=if(@last!=company,@num:=1,@num:=@num+1) 如果上一家公司不等於現在這家公司,就重置num為1,否則增加1

注意 需要先按公司排序 ,不然公司是亂的 序號就會不准

此時 這一步的時候,就得到了按分組排好序的資料

select id,company,salary,@num:=if(@last!=company,@num:=1,@num:=@num+1) as num,@last:=company 

from

(select id,company,salary from employee ) a ,

(select @num:=0,@last:=null) b order by company,salary

) a

然後關聯去取中位數, 先按公司分組,統計出最大條數,偶數的中位數的序號為 為** 最大數目/2 和最大數目/2+1 **

奇數的中位數為 (最大數目+1)/2

select count(1) as countnum,company,

case when count(1)%2=0 then count(1)/2 else null end as o1 ,

case when count(1)%2=0 then count(1)/2+1 else null end as o2,

case when count(1)%2=1 then (count(1)+1)/2 else null end as o3

from employee group by company

最後 用公司將這兩個進行關聯, 然後判斷每組的數目是奇數還是偶數來取值

select id,a.company,salary from

(select id,company,salary,@num:=if(@last!=company,@num:=1,@num:=@num+1) as num,@last:=company

from

(select id,company,salary from employee ) a ,

(select @num:=0,@last:=null) b order by company,salary

) ajoin

( select count(1) as countnum,company,

case when count(1)%2=0 then count(1)/2 else null end as o1 ,

case when count(1)%2=0 then count(1)/2+1 else null end as o2,

case when count(1)%2=1 then (count(1)+1)/2 else null end as o3

from employee group by company

) b on a.company=b.company where num=if(countnum%2=1,o3,o2) or num=if(countnum%2=0,o1,o3)

569 員工薪水中位數

employee 表包含所有員工。employee 表有三列 員工id,公司名和薪水。idcompany salary1a 23412a 3413a15 4a153145a 4516 a5137b 158b13 9b115410b 134511b 122112b 13413 c134514c 264...

leetcode569 員工薪水中位數

employee表包含所有員工。employee表有三列 員工id,公司名和薪水。id company salary 1 a 2341 2 a 341 3 a 15 4 a 15314 5 a 451 6 a 513 7 b 15 8 b 13 9 b 1154 10 b 1345 11 b 122...

LeetCode 569 員工薪水中位數

建表 drop table ifexists employee create table employee id int primary keyauto increment company char salary decimal insert into employee values 1 a 234...