我有 2 列,其中包含参与事务的用户 ID:source_id 和 destination_id。我正在构建一个函数来汇总由参与其中的任何用户(作为源或目标)分组的所有交易。
问题是,当我这样做时:
select count (*) from transactions group by source_id, destination_id
它会首先按来源分组,然后按目的地分组,我想将它们分组在一起。是否可以仅使用 SQL?
示例数据
source_user_id destination_user_id
1 4
3 4
4 1
3 2
期望的结果:
Id Count
4 - 3 (4 appears 3 times in any of the columns)
3 - 2 (3 appears 2 times in any of the columns)
1 - 2 (1 appear 2 times in any of the columns)
2 - 1 (1 appear 1 time in any of the columns)
正如您在示例结果中看到的,我想知道 id 在 2 个字段中的任何一个字段中出现的次数。
最佳答案
使用union all
将ID放入一列并获取计数。
select id,count(*)
from (select source_id as id from tbl
union all
select destination_id from tbl
) t
group by id
order by count(*) desc,id
关于mysql - 如何将 2 个不同的列分组在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47186939/