如何按组分隔两列计数?

时间:2017-05-02 05:48:31

标签: mysql sql group-by

当我这样做时,

SELECT id, gender, count(1)
FROM class_student
WHERE id = 1
GROUP BY gender

我得到了

id  gender    count
--------------------
1   female    10
1   male      5  

我怎么能得到这个?

id female male
---------------
1  10     5

以下查询是否是正确的方法?

SELECT
    id,
    (select count(1) from class_student
     where id = 1 AND gender='female') AS female,
    (select count(1) from class_student
     where id = 1 AND gender='male') AS male
FROM class_student
GROUP BY id

2 个答案:

答案 0 :(得分:1)

您可以在

时使用带有大小写的选项
  SELECT id
         , sum(case when gender = 'male' then 1 else 0 end) male, 
         , sum(case when gender = 'female' then 1 else 0 end) female
    FROM class_student
    WHERE id = 1
    GROUP BY id 

答案 1 :(得分:1)

您可以使用 CASES

SELECT id, SUM(case when gender = 'male' then 1 else 0 end) male, SUM(case when gender = 'female' then 1 else 0 end) female
    FROM CLASS_STUDENT
    WHERE id = 1
    GROUP BY id;