Find groups with matching rows

前端 未结 5 570
庸人自扰
庸人自扰 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:12

    try this,i think it is much easier and short code with just one partition function.

        declare @t table(Name varchar(50),Model varchar(50))
        insert into @t values
        ('Bob','Camry')
        ,('Bob','Civic')
        ,('Bob','Prius')
        ,('Kevin','Civic')
        ,('Kevin','Focus')
        ,('Mark','Civic')
        ,('Lisa','Focus')
        ,('Lisa','Civic')
    
        declare @input varchar(50)='Lisa'
    
        ;with 
    CTE1 AS
    (
    select name,model,ROW_NUMBER()over( order by name) rn
     from @t
    where name=@input
    )
    ,cte2 as
    (
    select t.name,t.Model
    ,ROW_NUMBER()over(partition by t.name order by t.name) rn3
    from @t t 
    inner JOIN
    cte1    c on t.Model=c.model 
    where   t.Name !=@input
    )
    select * from cte2 c
    where exists(select rn3 from cte2 c1 
    where c1.name=c.name and c1.rn3=(select max(rn) from cte1)
    )
    

提交回复
热议问题