如何计算单排?

时间:2013-03-08 13:58:07

标签: mysql sql pivot

我只是想了解mysql的知识

 mysql> SELECT species, sex, COUNT(*) FROM pet
        -> WHERE species = 'dog' OR species = 'cat'
        -> GROUP BY species, sex;

+---------+------+----------+
| species | sex  | COUNT(*) |
+---------+------+----------+
| cat     | f    |        1 |
| cat     | m    |        1 |
| dog     | f    |        1 |
| dog     | m    |        2 |
+---------+------+----------+

有可能得到吗?

+---------+-----------+-------------+
| species | malecount | femalecount |
+---------+-----------+-------------+
| cat     | 1         |       1     |
| dog     | 1         |       2     |
+---------+-----------+-------------+

在单个查询中?

2 个答案:

答案 0 :(得分:8)

这是MySQL中最短的答案。

SELECT  species,
        SUM(sex = 'm') maleCount,
        SUM(sex = 'f') femaleCount
FROM    pet
GROUP   BY species

MySQL还支持内联IF语句:

SELECT  species,
        SUM(IF(sex = 'm',1,0)) maleCount,
        SUM(IF(sex = 'f',1,0)) femaleCount
FROM    pet
GROUP   BY species

您还可以使用几乎适用于RDBMS的CASE

SELECT  species,
        SUM(CASE WHEN sex = 'm' THEN 1 ELSE 0 END) maleCount,
        SUM(CASE WHEN sex = 'f' THEN 1 ELSE 0 END) femaleCount
FROM    pet
GROUP   BY species

答案 1 :(得分:6)

您可以使用带有CASE表达式的聚合函数将 pivot 数据从行转换为列:

select species,
  sum(case when sex = 'm' then 1 else 0 end) maleCount,
  sum(case when sex = 'f' then 1 else 0 end) femaleCount
from pet
group by species