在我的数据库表中,我有两列,其中包含0或1。
我有type
和Gender
,其中type表示0 => teacher
和1 => student
,性别表示0 => male
和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
可以在一个查询中完成吗?如果是这样,怎么样?
答案 0 :(得分:3)
您可以使用CASE
功能使用SUM
:
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;
答案 1 :(得分: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);
答案 2 :(得分: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;
答案 3 :(得分:0)
是的,你可以。您是否尝试过将每个SQL语句放在一起?
SQL1 as fld1, SQL2 as fld2, someOtherFieldsIfNeeded FROM ...