[英]Two mysql counts with two different where conditions in one query
I have a table with two columns namely teacherid
and sub_group
. 我有一个包含两列的表,即teacherid
和sub_group
。 Now, sub_group can have values ranging from 0-100 where 0 means lectures for teachers and anything greater than 0 means tutorials. 现在,sub_group的值可以在0-100之间,其中0表示为教师讲课,大于0的则表示教程。 I want to be able to calculate the number of lectures and tutorials grouped by teachers. 我希望能够计算出按老师分组的讲座和辅导的数量。
So far i have two queries like 到目前为止,我有两个查询
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
I want to combine the results of the two into one resultset, something like 我想将两者的结果合并为一个结果集,例如
teacher lectures tutorials
1 15 10
2 14 8
Please suggest... 请建议...
You can use the aggregate function with a CASE
expression: 您可以将聚合函数与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;
This will give you 3 columns, the teacherId
and then the total lectured and tutorials in separate columns. 这将为您提供3列,即teacherId
,然后在单独的列中提供全部的teacherId
和教程。
This relies on COUNT ignoring NULLs (the missing ELSE in the CASE expression) 这依赖于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
You can use CASE
statement to get what you want here. 您可以使用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
Almost same solution, as other guys offered, but with IF function: 与其他人提供的解决方案几乎相同,但具有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
For me it's easier to read 对我来说更容易阅读
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.