的MySQL 我有一张桌子,两列专栏' N'和列' V',' V'是1或0(可能是其他值,所以不要使用SUM())。
mysql> select * from counter;
+------+------+
| N | V |
+------+------+
| A | 0 |
......
| D | 1 |
+------+------+
我希望计算多少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 |
+------+------+----------+
问题是我想显示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 |
+------+------+----------+
我怎样才能做到这一点?如果表格很大,如何获得最佳表现?
答案 0 :(得分:2)
这是在cartesian product
和N
之间使用V
创建cross join
的一个选项。然后,您可以使用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