使用MySQL计算条件

时间:2014-12-11 06:37:20

标签: mysql sql

我是mySQL的新手。

我想显示下表的计数表,如下所示:

表:测试

create table test
(
age int,
sex text
);

插入一些记录:

insert into test values(10,'Male');
insert into test values(15,'Male');
insert into test values(20,'Male');
insert into test values(25,'Male');
insert into test values(30,'Male');
insert into test values(10,'Female');
insert into test values(15,'Female');
insert into test values(40,'Male');
insert into test values(50,'Female');
insert into test values(60,'Female');

注意:现在我想在表格中显示年龄范围内男性和女性的数量。

预期结果

 Age-Range   sex    count
 ------------------------
  10-20      Male    3
  10-20      Female  2
  25-40      Male    3
  45-60      Female  2

1 个答案:

答案 0 :(得分:2)

虽然在mysql中计算一组中的男性和女性很容易。您可以使用条件sum例如

select 
age,
sum(sex='Male') as male_count
sum(sex='Female') as female_count
from test
group by age ;

但在你的情况下你也需要考虑范围,所以它不是直截了当的。这是一种可以实现您所看到的目标的方法,但可能还有其他更好的方法。

select 
p.`range`,
p.sex,
sum(p.`count`) as `count`
from
(
 select 
  x.`range`,
  y.`sex`,
  y.`age`,
  y.`count` from( 
    select '10-20' as `range`,20 as `upper` ,10 as `lower`
    union all 
    select '25-40' as `range`,40 as `upper` ,25 as `lower`
    union all 
    select '45-60' as `range`,60 as `upper` ,45 as `lower`
  )x
  left join(
    select
    sex,
    count(*) as `count`,
    age from test
    group by age,sex

  )y
  on y.age >= x.`lower` and y.age <= x.`upper`
)p

group by p.`range`,p.sex
;