当前位置:网站首页>[MySQL] using SQL to find the median

[MySQL] using SQL to find the median

2022-06-22 12:32:00 Tanyue Jianzhi Dachang

use sql Find the median

1. Build table

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

INSERT INTO kwan.employee_information
VALUES (' Sampson ', 400000);
INSERT INTO kwan.employee_information
VALUES (' mike ', 30000);
INSERT INTO kwan.employee_information
VALUES (' white ', 20000);
INSERT INTO kwan.employee_information
VALUES (' Arnold ', 20000);
INSERT INTO kwan.employee_information
VALUES (' Smith. ', 20000);
INSERT INTO kwan.employee_information
VALUES (' Laurence ', 15000);
INSERT INTO kwan.employee_information
VALUES (' Hudson ', 15000);
INSERT INTO kwan.employee_information
VALUES (' Kent ', 10000);
INSERT INTO kwan.employee_information
VALUES (' Baker, ', 10000);
INSERT INTO kwan.employee_information
VALUES (' Scott ', 10000);

2. Median sql

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

3. analysis

  • First, Cartesian product the same table join
  • adopt 2 individual having Conditions filter out the data that meets the requirements
  • De duplication result set
  • Half of the median must be greater than or equal to the median , Half the number is less than or equal to the median – Key points
原网站

版权声明
本文为[Tanyue Jianzhi Dachang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221202564268.html