mysql - 如何将 2 个不同的列分组在一起

标签 mysql sql

我有 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/

相关文章:

java - 没有@Query的Spring存储库

mysql - SQL获取每个PlayerID的行总和

java - HQL 查询从多个 Item 对象实例检索通用标签

mysql - 我正在尝试使用 CakePHP 和 MySQL 找到一种 "simple"存储图像(以及有关图像的数据)的方法。这段代码让我有点困惑

php - php/mysql 查询的值不正确

java - 两个 docker 容器之间的通信问题

sql - 当我尝试按照文档更改 root 密码时,出现 SQL 语法错误或密码未更新

mysql - SQL查询LIKE语句错误

sql - 从数字中删除尾随零

MySQL:SELECT DISTINCT 多列