用sql求中位数

1.建表

CREATE TABLE kwan.employee_information
(
    name   VARCHAR(16) PRIMARY KEY,
    income INTEGER NOT NULL
);

INSERT INTO kwan.employee_information
VALUES ('桑普森', 400000);
INSERT INTO kwan.employee_information
VALUES ('迈克', 30000);
INSERT INTO kwan.employee_information
VALUES ('怀特', 20000);
INSERT INTO kwan.employee_information
VALUES ('阿诺德', 20000);
INSERT INTO kwan.employee_information
VALUES ('史密斯', 20000);
INSERT INTO kwan.employee_information
VALUES ('劳伦斯', 15000);
INSERT INTO kwan.employee_information
VALUES ('哈德逊', 15000);
INSERT INTO kwan.employee_information
VALUES ('肯特', 10000);
INSERT INTO kwan.employee_information
VALUES ('贝克', 10000);
INSERT INTO kwan.employee_information
VALUES ('斯科特', 10000);

2.中位数sql

-- 查询sql
select avg(distinct income)
from (select t1.income
      from kwan.employee_information t1,
           kwan.employee_information t2
      group by t1.income
               -- s1 的条件
      having sum(case when t2.income >= t1.income then 1 else 0 end)
          >= count(*) / 2.0
         -- s2的条件
         and sum(case when t2.income <= t1.income then 1 else 0 end)
          >= count(*) / 2.0) tmp;

3.解析

  • 先对同一个表进行笛卡尔积join
  • 通过2个having条件筛选出符合要求的数据
  • 去重结果集
  • 中位数一定有一半的数大于等于中位数,一半的数小于等于中位数–关键点
Logo

华为云1024程序员节送福利,参与活动赢单人4000元礼包,更有热门技术干货免费学习

更多推荐