简体   繁体   中英

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> select * from counter;
+------+------+
| N    | V    |
+------+------+
| A    |    0 |
......
| D    |    1 |
+------+------+

I wish to count how many 0 and how many 1, as below:

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:

+------+------+----------+
| 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 . Then you can use an outer join to get all results:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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