【SQL】利用HAVING取众数和中位数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/NextAction/article/details/80421854

1. 创建测试表及测试数据

CREATE TABLE graduates (
  name varchar(255) ,
  income int4(255) 
);

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

2. 取众数

select income,count(*) cnt 
from graduates
group by income
having count(*) >= (
select max(cnt) from (select count(*) cnt from graduates group by income) tmp
);

3. 取中位数

select AVG(DISTINCT income)
from (
select T1.income from graduates T1,graduates T2
group by T1.income
having sum(case when T2.income >= T1.income then 1 else 0 end) >= count(*)/2
and sum(case when T2.income <= T1.income then 1 else 0 end) >= count(*)/2
) tmp;

没有更多推荐了,返回首页