在同一列上计数查询

时间:2014-11-02 20:52:11

标签: sql

以下是两个SQL表:

  • 课堂(1-100),
  • 性别(男/女)

我想计算每个教室的每个性别。我希望查询结果为:

Classroom | CountMale | CountFemale
          |           |
          |           |
          |           |

如何计算?

2 个答案:

答案 0 :(得分:1)

SELECT Classroom,
SUM(CASE WHEN Gender='male' THEN 1 ELSE 0 END) as CountMale,
SUM(CASE WHEN Gender='female' THEN 1 ELSE 0 END) as CountFemale
FROM t
GROUP BY Classroom

答案 1 :(得分:0)

也许是这样的:

SELECT Classroom, 
      SUM(CASE WHEN GENDER = 'MALE' THEN 1 ELSE 0 END) AS CountMale,
      SUM(CASE WHEN GENDER = 'FEMALE' THEN 1 ELSE 0 END) AS CountFemale
FROM TABLE
GROUP BY Classroom

更改文字。