Skip to content
Advertisement

How to select DISTINCT records based on multiple columns and without considering their order

I’m currently working on a SQL Server database and I would need a query that returns pairs of customers with the same city from a table that has this structure

and this sample data

I have tried defining a query that joins the Customer table itself

but it gives me a table that looks like this

with duplicated rows but with swapped customers.

My question is how would I have to do to select those rows once (e.g. for the first two results, it would be great only the first or the second row).

This would be an example of the expected result

Advertisement

Answer

I think I understand what you are looking for but it seems over simplified to your actual problem. Your query you posted was incredibly close to working. You can’t reference columns by their alias in the where predicates so you will need to use the string concatenation you had in your column. Then you can simply change the <> to either > or < so you only get one match. This example should work for your problem as I understand it.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement