两个mysql计数在一个查询中有两个不同的where条件

时间:2013-06-17 15:11:15

标签: mysql count

我有一个包含两列的表,即teacheridsub_group。现在,sub_group的值可以是0-100,其中0表示教师讲座,大于0表示教程。我希望能够计算出由教师分组的讲座和教程的数量。

到目前为止,我有两个问题,比如

SELECT teacherid, count(*) as lectures FROM `ttresponsibility` where sub_group = 0
group by teacherid

SELECT teacherid, count(*) as tutorials FROM `ttresponsibility` where sub_group > 0
group by teacherid

我想将两者的结果合并为一个结果集,例如

teacher    lectures   tutorials

1           15         10
2           14         8

请建议......

4 个答案:

答案 0 :(得分:4)

您可以将聚合函数与CASE表达式一起使用:

select teacherid,
  sum(case when sub_group = 0 then 1 else 0 end) lectures,
  sum(case when sub_group > 0 then 1 else 0 end) tutorials
from `ttresponsibility`
group by teacherid;

这将为您提供3列teacherId,然后在单独的列中提供总课程和教程。

答案 1 :(得分:1)

这依赖于COUNT忽略NULL(CASE表达式中缺少的ELSE)

SELECT
   teacherid,
   count(CASE WHEN sub_group = 0 THEN 1 END) as lectures
   count(CASE WHEN sub_group > 0 THEN 1 END) as tutorials 
FROM
   `ttresponsibility`
group by teacherid

答案 2 :(得分:0)

您可以使用CASE语句来获取您想要的内容。

SELECT
    teacherid,
    SUM(CASE WHEN sub_group = 0 THEN 1 ELSE 0 END CASE) as lectures,
    SUM(CASE WHEN sub_group > 0 THEN 1 ELSE 0 END CASE) as tutorials,
FROM ttresponsibility
GROUP BY teacherid

答案 3 :(得分:0)

与其他人提供的几乎相同的解决方案,但具有IF功能:

    SELECT
        teacherid,
        SUM(IF(sub_group = 0, 1, 0)) as lectures,
        SUM(IF(sub_group > 0, 1, 0)) as tutorials,
    FROM ttresponsibility
    GROUP BY teacherid

对我来说,它更容易阅读