Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group by column pairs without considering their order

I have a table like this:

Name1 Name2 Address1 Address2
Jane Mary 1st Street 2nd Street
Mary Jane 2nd Street 1st Street
Aubery Mary 3rd Street 2nd Street
Sindy Simon 4th Street 5th Street

I would like row 1 and 2 to be captured as the same in a GROUP BY statement, that is, row 1 and 2 represents the same information but in a different order (So their count would be 2) with the two pairs being Name1, Address1 & Name2, Address2.

How would I go about this?

like image 838
Jack Avatar asked Sep 16 '25 01:09

Jack


1 Answers

We can aggregate using a LEAST/GREATEST trick:

SELECT
    LEAST(Name1, Name2) AS Name1,
    GREATEST(Name1, Name2) AS Name2,
    LEAST(Address1, Address2) AS Address1,
    GREATEST(Address1, Address2) AS Address2,
    COUNT(*) AS cnt
FROM yourTable
GROUP BY 1, 2, 3, 4;

screen capture from demo link below

Demo

like image 105
Tim Biegeleisen Avatar answered Sep 18 '25 18:09

Tim Biegeleisen