简体   繁体   English

SQL | 如何 GROUP BY 并根据两个条件获得不同的 COUNT?

[英]SQL | How to GROUP BY and get different COUNT's subject to two conditions?

Given a table with two attributes "ID" and "bug" where "bug" is valued either 0 or 1, meaning给定一个包含两个属性“ID”和“bug”的表,其中“bug”的值为 0 或 1,这意味着
person with that "ID" either made a commit with a bug or with no bug.具有该“ID”的人要么提交了错误,要么没有错误。 The same "ID" may re-appear in the table.相同的“ID”可能会重新出现在表中。 The task is to print the distinct ID's with the number of buggy commits and non-buggy commits.任务是打印不同的 ID,其中包含错误提交和非错误提交的数量。 The schema and an example table are as follows架构和示例表如下

CREATE TABLE commits (
ID INT NOT NULL,
bug INT);

The table is该表是

 _ID__|bugs_
 | 121|1|
 | 121|1|
 | 121|0|
 | 111|1|
 | 111|0|
 | 111|1|
 | 131|0|
 | 131|0|
 | 121|1|
 | 111|0|
 | 121|1|
 | 111|0|
 | 121|1|
 | 131|0|
 --------

The solution should be(not exactly, but like this)解决方案应该是(不完全是,但像这样)

111|3|4
121|6|2
131|1|5

The way I went about it was to create two tables, one where "bug" equals 1 and the other where it is 0. Then used GROUP BY and count on these to get the tables with buggy and non buggy commits.我的方法是创建两个表,一个“错误”等于 1,另一个为 0。然后使用 GROUP BY 并依靠这些来获得有错误和无错误提交的表。 Then I INNER JOINED them using "ID".然后我使用“ID”INNER JOINED 他们。 Finally, accessed the ID and the count of "buggy" & "notbuggy" columns with COUNT().最后,使用 COUNT() 访问 ID 和“buggy”和“notbuggy”列的计数。 This was my Query, which worked这是我的查询,有效

select distinct buggy.id,buggy.buggycount,notbuggy.notbuggycount from 
(select id,count(bug) as buggycount 
from (select id,bug from commits where bug = 1) a group by id) buggy 
inner join 
(select id,count(bug) as notbuggycount
from (select id,bug from commits where bug = 0) a group by id) notbuggy
where buggy.id = notbuggy.id
order by buggy.id;

Is there a better and shorter way to do this?有没有更好更短的方法来做到这一点? Ideally, without any INNER JOIN.理想情况下,没有任何 INNER JOIN。 Thank You.谢谢你。

Use conditional aggregation:使用条件聚合:

SELECT id,
       SUM(bug = 0) notbuggycount,
       SUM(bug = 1) buggycount
FROM commits
GROUP BY id;

or:或者:

SELECT id,
       SUM(1 - bug) notbuggycount,
       SUM(bug) buggycount
FROM commits
GROUP BY id;

See the demo .请参阅演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM