Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading