mysql值大于值数量的百分比

时间:2018-07-28 10:26:36

标签: mysql sql percentage

我想找到年龄大于某年所有值的n%的姓名。 这是桌子:

mysql> select * from cust;
+------+------+------+
| name | age  | year |
+------+------+------+
| toni |   21 | 2016 |
| robi |   22 | 2016 |
| deni |   23 | 2016 |
| jeki |   24 | 2016 |
| yodi |   25 | 2016 |
| rino |   26 | 2016 |
| goli |   27 | 2016 |
| tobi |   28 | 2016 |
| lemi |   29 | 2016 |
| lora |   30 | 2016 |
| riko |   25 | 2017 |
| soni |   26 | 2017 |
| bino |   27 | 2017 |
| kola |   28 | 2017 |
| zoki |   29 | 2017 |
| mera |   30 | 2017 |
| noki |   31 | 2017 |
| peni |   32 | 2017 |
| vino |   33 | 2017 |
| heri |   34 | 2017 |
+------+------+------+

DDL:

create table tbl ( name varchar(10), age int, year  int);
insert into tbl values
('toni', 21, 2016 ),
('robi', 22, 2016 ),
('deni', 23, 2016 ),
('jeki', 24, 2016 ),
('yodi', 25, 2016 ),
('rino', 26, 2016 ),
('goli', 27, 2016 ),
('tobi', 28, 2016 ),
('lemi', 29, 2016 ),
('lora', 30, 2016 ),
('riko', 25, 2017 ),
('soni', 26, 2017 ),
('bino', 27, 2017 ),
('kola', 28, 2017 ),
('zoki', 29, 2017 ),
('mera', 30, 2017 ),
('noki', 31, 2017 ),
('peni', 32, 2017 ),
('vino', 33, 2017 ),
('heri', 34, 2017 );

我想找到2017年的名字,该年龄大于2016年所有年龄的60%。我做了类似的事情

select name from cust where year=2017 and age>
    (SELECT age
    FROM    (
        SELECT cust.*, @counter := @counter +1 AS counter
        FROM (select @counter:=0) AS initvar, cust where year=2016
        ORDER BY age DESC   
    ) AS X
    where counter <= (60/100 * @counter) 
    ORDER BY age DESC);

我知道这是错误的,但是您知道我的意思是比较主查询之间的值 和子查询,但我希望该子查询超过1行。 是否有一个有效的解决方案,但与上面类似?

编辑:这是我想要的输出:

+------+
| name |
+------+
| soni |
| bino |
| kola |
| zoki |
| mera |
| noki |
| peni |
| vino |
| heri |
+------+

2 个答案:

答案 0 :(得分:1)

要在2016年的MySQL中(第8版之前)找到第60个百分位数:

select min(age)
from (select c.*, (@rn := @rn + 1) as rn
      from (select c.*
            from cust c
            where year = 2016
            order by age
           ) c cross join
           (select @rn := 0) params
     ) c
where rn >= @rn * 0.6;

要查找2017年的相应年龄,您可以在以下位置join

select c.* from cust c join
     (select min(age) as age_2016
      from (select c.*, (@rn := @rn + 1) as rn
            from (select c.*
                  from cust c
                  where year = 2016
                  order by age
                 ) c cross join
                 (select @rn := 0) params
           ) c
      where rn >= @rn * 0.6
     ) cc
     on c.age >= cc.age_2016 where year = 2017;

答案 1 :(得分:0)

尝试以下简单查询:

select name
from tbl t
where (select count(*) from tbl where year = 2016 and age <= t.age) /
      (select count(*) from tbl where year = 2016) >= 0.6 
  and year = 2017;

where子句中,您只需将2016年的年轻人数除以2016年的所有人,即可得出百分比(0.01.0)。因此,只需要取那些大于或等于0.6的值即可。