如何在一个查询中获取比率?

时间:2014-06-04 15:54:50

标签: mysql aggregate-functions aggregate

我有下表values

id | value | team | is_whatever
-------------------------------
 1 |     2 |    1 | true
 2 |     7 |    1 | true
 3 |    10 |    1 | NULL
 4 |     3 |    2 | NULL
 5 |    23 |    2 | true

现在,我想获取按COUNT()分组的team行,并获取is_whatever = true的比率。所以预期的结果应该是

team | count | ratio
--------------------
   1 |     3 | 0.66
   2 |     2 |  0.5

我的第一种方法是按team分组,然后按is_whatever分组。但我不知道如何获取ratio列:

SELECT
    `team`,
    COUNT(*) AS `count`,
    COUNT(`is_whatever`) AS `ratio`
FROM `values`
GROUP BY `team`, `is_whatever`

然后我考虑加入桌子两次:<​​/ p>

SELECT
    `v1`.`team`,
    COUNT(`v1`.*) AS `count`,
    COUNT(`v2`.*) AS `ratio`
FROM `values` `v1`
JOIN `values` `v2` ON `v1`.`id` = `v2`.`id`
WHERE `v1`.`is_whatever` = true
GROUP BY `team`

但是这两个问题并没有让我达到理想的结果。知道如何在一个查询中获取它吗?

2 个答案:

答案 0 :(得分:2)

drop table if exists v;
create table v (id integer, value integer, team integer, is_whatever enum('true','false'));
insert into v (id,value,team,is_whatever) values 
('1','2','1','true'),
('2','7','1','true'),
('3','10','1',NULL),
('4','3','2',NULL),
('5','23','2','true');

select team, ct as count, cw/ct as ratio
from
(
select team,count(team) as ct, count(is_whatever) as cw
from v 
group by team
) counts

结果:

1;3;0.6667
2;2;0.5000

答案 1 :(得分:1)

脱离我的头顶 您可以在Count

中放置一个表达式
Select team, NumberOf as 'Count', NumberOfWhatevers / NumberOf as ratio From
(
  Select team, Count(is_whatever = true) as NumberOfWhatevers,Count(*) as NumberOf 
  From values Group By team
) counts