简体   繁体   English

MySQL:如何使用分组依据显示计数为0的行?

[英]MySQL: how to show rows where count is 0 using group by?

MySQL I have a table, two columns column'N' and column'V', the value of 'V' is either 1 or 0 (may be other values, so don't use SUM()). MySQL我有一个表,两列column'N'和column'V','V'的值是1或0(可能是其他值,所以不要使用SUM())。

mysql> select * from counter;
+------+------+
| N    | V    |
+------+------+
| A    |    0 |
......
| D    |    1 |
+------+------+

I wish to count how many 0 and how many 1, as below: 我希望计算一下0和1,如下所示:

mysql> select N, V, count(V) from counter group by N,V;
+------+------+----------+
| N    | V    | count(V) |
+------+------+----------+
| A    |    0 |        2 |
| A    |    1 |        7 |
| B    |    0 |        7 |
| B    |    1 |        2 |
| C    |    0 |        3 |
| D    |    1 |        3 |
+------+------+----------+

The problem is I want to show rows where the count(V) is 0. In this case, my expected result should look like as below: 问题是我想显示count(V)为0的行。在这种情况下,我的预期结果应如下所示:

+------+------+----------+
| N    | V    | count(V) |
+------+------+----------+
| A    |    0 |        2 |
| A    |    1 |        7 |
| B    |    0 |        7 |
| B    |    1 |        2 |
| C    |    0 |        3 |
| C    |    1 |        0 | **
| D    |    0 |        0 | **
| D    |    1 |        3 |
+------+------+----------+

How can I achieve this? 我该如何实现? And if the table is large, how to get the best performance? 如果桌子很大,如何获得最佳性能?

Here's one option creating a cartesian product between N and V with a cross join . 这是一个使用cross joinNV之间创建cartesian product选项。 Then you can use an outer join to get all results: 然后,您可以使用outer join来获取所有结果:

select t.n, t.v, count(c.n)
from (select distinct t1.n, t2.v
      from counter t1 cross join counter t2) t left join 
   counter c on t.n = c.n and t.v = c.v
group by t.n, t.v

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

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