Find groups with matching rows

前端 未结 5 582
庸人自扰
庸人自扰 2020-12-22 01:11

I have a table of people (CarOwners) and the types of cars they own

+-------+-------+
| Name  | Model |
+-------+-------+
| Bob   | Camry |
| Bo         


        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-22 02:00

    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'
    

提交回复
热议问题