首页 > 解决方案 > MySQL 计算 2 个不同的列都与一个 id 相关

问题描述

我有一些用户,例如用户 10、20 和 30;并且可以在a栏或b栏注册;我需要计算每个用户在 a 列上有多少行(简单 count() ),但我还想计算在同一用户上但在 b 列上有多少行;我的挑战是我在同一行的 a 列和 b 列中有不同的用户。

+----+----+------+------+
| id | a  | b    | c    |
+----+----+------+------+
|  1 | 10 | NULL | NULL |
|  2 | 10 |   20 | NULL |
|  3 | 20 | NULL | NULL |
|  4 | 10 |   30 | NULL |
|  5 | 20 | NULL | NULL |
|  6 | 30 |   20 | NULL |
|  7 | 10 |   20 | NULL |
+----+----+------+------+

我努力了:

select a, count(if(a is not null,1,null)) aC, count(if(b is not null, 1, null)) bC 
from test 
group by a;

但如果不为空,它会在 b 列上返回:

+----+----+----+
| a  | aC | bC |
+----+----+----+
| 10 |  4 |  3 |
| 20 |  2 |  0 |
| 30 |  1 |  1 |
+----+----+----+

我需要的是

+----+----+----+
| a  | aC | bC |
+----+----+----+
| 10 |  4 |  0 |
| 20 |  2 |  3 |
| 30 |  1 |  1 |
+----+----+----+

我已经设法通过带有 where 的嵌套选择来获得结果,但只有在我查询特定用户时才有效(结果只有一行)。

标签: mysql

解决方案


这是一种方法:

select a 
    , count(case when col ='A' then 1 end) Acount
    , count(case when col ='B' then 1 end) BCount
from (
   select a , 'A' col
   from tablename
   union all 
   select b , 'B'
   from tablename 
) t 
group by a 

推荐阅读