-1

在我的数据库表中,我有两列分别为 0 或 1。

我有typeand Gender,其中 type 表示0 => teacherand1 => student表示性别:0 => maleand 1 => female

如何编写单个 sql 查询来获取教师、学生、男性和女性的数量?

现在我有:

select COUNT(type) as teachers from my_table where type = 0; // Teachers
select COUNT(type) as students from my_table where type = 1; // Students
select COUNT(gender) as males from my_table where type = 0; // Males
select COUNT(gender) as females from my_table where type = 1; // Females

可以在一个查询中完成吗?如果是这样,怎么做?

4

4 回答 4

3

您可以使用CASE该 usingSUM功能:

SELECT SUM(CASE type WHEN  1 THEN 1 ELSE 0 END) AS students,
       SUM(CASE type WHEN  0 THEN 1 ELSE 0 END) AS teachers,
       SUM(CASE gender WHEN 1 THEN 1 ELSE 0 END) AS females,
       SUM(CASE gender WHEN 0 THEN 1 ELSE 0 END) AS males
FROM my_table;

您也可以使用COUNT函数而不是SUM这样:

SELECT COUNT(CASE type WHEN  1 THEN 1 ELSE NULL END) AS students,
       COUNT(CASE type WHEN  0 THEN 1 ELSE NULL END) AS teachers,
       COUNT(CASE gender WHEN 1 THEN 1 ELSE NULL END) AS females,
       COUNT(CASE gender WHEN 0 THEN 1 ELSE NULL END) AS males
FROM my_table;

See this SQLFiddle

于 2012-09-05T10:46:56.590 回答
1

这样,您可以在单个查询中完成。如果表中只有两种类型的数据,则无需在子句中指定IN条件:WHERE

SELECT SUM(IF(type = 1, 1, 0)) as students,
       SUM(IF(type = 0, 1, 0)) as teachers,
       SUM(IF(gender = 1, 1, 0)) as females,
       SUM(IF(gender = 0, 1, 0)) as males
FROM my_table
WHERE type IN(0,1)
      AND gender IN(0,1);
于 2012-09-05T10:42:33.880 回答
1

您可以使用子查询来实现这一点。

SELECT COUNT(type) AS students,
    (SELECT COUNT(type) FROM my_table WHERE type = 0) As teachers,
    (SELECT COUNT(gender) FROM my_table WHERE gender = 1) AS females,
    (SELECT COUNT(gender) FROM my_table WHERE gender = 0) AS males
FROM my_table WHERE type = 1;
于 2012-09-05T10:45:25.410 回答
0

是的你可以。您是否尝试过将每个 SQL 语句放在一起?
SQL1 as fld1, SQL2 as fld2, someOtherFieldsIfNeeded FROM ...

于 2012-09-05T10:42:21.383 回答