当我这样做时,
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
答案 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;