2

我只是想了解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     |
+---------+-----------+-------------+

在单个查询中?

4

2 回答 2

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

您还可以使用CASEwhich 适用于几乎 RDBMS:

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
于 2013-03-08T13:59:06.227 回答
6

您可以使用带有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
于 2013-03-08T13:59:29.580 回答