mysql - 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 的嵌套选择来获得结果,但只有在我查询特定用户时才有效(结果只有一行)。
解决方案
这是一种方法:
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
推荐阅读
- ruby-on-rails - 连接两个哈希值
- python - 连接时比较字符串
- php - want to get difference between two values
- amazon-web-services - SQS 属性作为变量
- android - 数据绑定问题 - 错误找不到符号
- facebook - Facebook 消息到页面
- excel - 将多个字符串连接到单个 msgbox
- r - 查找时间戳向量更改时区的位置
- javascript - 如果可能的话,我需要一个匹配以下内容的正则表达式,以及如何使用 javascript 或 node js 包对其进行测试
- r - 无法在箱线图中设置轴的间隔:RStudio