对于MySQL的内容在前期有做一些讲解,伙伴们可以翻历史文章查看,近期讲解多的是Excel的相关内容,本期将以案例的形式回顾以往讲解过MySQL的内容,同时也会融入一些新的知识,一起看看吧~
* 案例需求
:在tese数据库中建立T001表并取其中的中位数(若记录数为奇数,取一条,否则取两条)
use test;
CREATE TABLE T001 (ID int primary key,company varchar(20),salary varchar(20));
insert into T001 VALUES(2,'A',9410);
insert into T001 VALUES(3,'A',10050);
insert into T001 VALUES(4,'A',15314);
insert into T001 VALUES(5,'A',8451);
insert into T001 VALUES(6,'A',9513);
insert into T001 VALUES(7,'B',10005);
insert into T001 VALUES(8,'B',13000);
insert into T001 VALUES(9,'B',11540);
insert into T001 VALUES(10,'B',10345);
insert into T001 VALUES(11,'B',12210);
insert into T001 VALUES(12,'B',9234);
insert into T001 VALUES(13,'C',12000);
insert into T001 VALUES(14,'C',8900);
insert into T001 VALUES(15,'C',900);
insert into T001 VALUES(16,'C',10100);
insert into T001 VALUES(17,'C',8000);
SELECT
ID,
company,
salary
FROM
( SELECT *,
ROW_NUMBER() over ( PARTITION BY company ORDER BY salary ) RNk,
COUNT(*) over ( PARTITION BY company ) NUM FROM `t001` ) T
WHERE
((
num % 2 = 1
AND RNK = FLOOR( NUM / 2 )+ 1
)
OR ( NUM % 2 = 1 AND RNK = FLOOR( NUM / 2 ) OR RNK = FLOOR( NUM / 2 )+ 1 ))
01
:【RNK】:COMPANY进行分组升序排列 —— 之前有讲解
02
:【NUM】:COMPANY进行统计个数 —— 之前有讲解
WHERE条件说明
:
如果【NUM】的值为奇数那么【RNK】=【NUM】/2+1,如果【NUM】的值为偶数那么【RNK】=【NUM】/2+1 或 【RNK】=【NUM】/2
本期内容完结,后期也将讲解更多案例,通过案例加深知识理解喔~