Home > Enterprise >  Group by and counting the number of unique values across multiple columns (mysql)
Group by and counting the number of unique values across multiple columns (mysql)

Time:03-03

ID ArrivalPort DeparturePort
1  A           B
1  A           C
2  A           B
2  C           D

How do I do a unique/distinct count of both the ArrivalPort and DeparturePort by ID?

Out
ID   Count
1    3
2    4

Thanks!

CodePudding user response:

You can do a union in a derived tabled then count:

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

  • Related