如何将两列数按组分开?

时间:2021-01-29 22:30:52

When I do this,

当我这样做时,

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

I get

我得到

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

How can I get this?

我怎么能得到这个?

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

Is following query is the right way to do this?

执行查询是正确的方法吗?

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 个解决方案

#1


1  

you can use a select with case when

您可以使用select with case when

  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 

#2


1  

You can use 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;

#1


1  

you can use a select with case when

您可以使用select with case when

  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 

#2


1  

You can use 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;