I have a table of people (CarOwners
) and the types of cars they own
+-------+-------+
| Name | Model |
+-------+-------+
| Bob | Camry |
| Bo
One way to do this is comparing the ordered concatenated model value for each name.
with cte as (
select name,model,
STUFF((
SELECT ',' + t2.model
FROM t t2
WHERE t1.name=t2.name
ORDER BY model
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 1, '') concat_value
from t t1
)
select distinct x2.name,x2.model
from cte x1
join cte x2 on x1.concat_value=x2.concat_value and x1.name<>x2.name
where x1.name='Kevin'
If your version of SQL Server supports STRING_AGG, the query can be simplified as
with cte as (
select name,model,
STRING_AGG(model,',') WITHIN GROUP(ORDER BY model) as concat_value
from t t1
)
select distinct x2.name,x2.model
from cte x1
join cte x2 on x1.concat_value=x2.concat_value and x1.name<>x2.name
where x1.name='Kevin'