Py学习  »  DATABASE

分组并计算多列中唯一值的数量(mysql)

TYL • 3 年前 • 1238 次点击  
ID ArrivalPort DeparturePort
1  A           B
1  A           C
2  A           B
2  C           D

如何对这两种情况进行唯一/不同的计数 ArrivalPort DeparturePort 通过 ID ?

Out
ID   Count
1    3
2    4

谢谢

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/127957
 
1238 次点击  
文章 [ 1 ]  |  最新文章 3 年前
Zakaria
Reply   •   1 楼
Zakaria    3 年前

可以在派生表中进行并集,然后进行计数:

select ID, count(distinct Port) as Count from
(select id, ArrivalPort as Port from table_name
union all select id, DeparturePort from table_name) t
group by id;

Fiddle