如何将2个不同的列组合在一起

时间:2017-11-08 18:18:19

标签: mysql sql

我有两列用户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个字段中的任何一个的次数。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

编辑添加:感谢您澄清您的问题。以下不是您需要的。

听起来你想使用连接函数。 https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_concat

GROUP BY CONCAT(source_id,"_",destination_id)

下划线旨在区分" source_id = 1,destination_id = 11" from" source_id = 11,destination_id = 1"。 (我们希望它们分别为1_11和11_1。)如果您希望这些ID包含下划线,则必须以不同方式处理,但我认为它们是整数。

答案 2 :(得分:0)

可能看起来像这样。

Select id, count(total )  from
(select source_id as id, count (destination_user_id) as total from transactions group by source_id
union
select destination_user_id as id , count (source_id) as total from transactions group by destination_user_id ) q group by id