SQL |如何根据两个条件进行 GROUP BY 并获取不同的 COUNT?
给定一个具有两个属性“ID”和“bug”的表,其中“bug”的值为 0 或 1,含义
具有该“ID”的人要么进行了有错误的提交,要么没有错误的提交。相同的“ID”可能会再次出现在表中。任务是打印不同的 ID 以及有错误提交和无错误提交的数量。架构和示例表如下
CREATE TABLE commits (
ID INT NOT NULL,
bug INT);
表是
_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|
--------
解决方案应该是(不完全是这样,但像这样)
111|3|4
121|6|2
131|1|5
我的方法是创建两个表,一个表中“bug”等于 1,另一个表中“bug”等于 0然后使用 GROUP BY 并依靠这些来获取有错误和无错误提交的表。然后我用“ID”内在地加入了他们。最后,访问了“buggy”的 ID 和计数。带有 COUNT() 的“notbuggy”列。这是我的查询,它有效
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;
有没有更好、更短的方法来做到这一点?理想情况下,没有任何 INNER JOIN。 谢谢。
Given a table with two attributes "ID" and "bug" where "bug" is valued either 0 or 1, meaning
person with that "ID" either made a commit with a bug or with no bug. The same "ID" may re-appear in the table. The task is to print the distinct ID's with the number of buggy commits and non-buggy commits. 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. Then I INNER JOINED them using "ID". Finally, accessed the ID and the count of "buggy" & "notbuggy" columns with COUNT(). 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.
Thank You.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用条件聚合:
或者:
请参阅演示。
Use conditional aggregation:
or:
See the demo.