SQL Server - INNER JOIN WITH DISTINCT

后端 未结 6 1204
小蘑菇
小蘑菇 2020-12-16 11:28

I am having a hard time doing the following:

select a.FirstName, a.LastName, v.District
from AddTbl a order by Firstname
inner join (select distinct LastName         


        
6条回答
  •  北荒
    北荒 (楼主)
    2020-12-16 12:10

    You can use CTE to get the distinct values of the second table, and then join that with the first table. You also need to get the distinct values based on LastName column. You do this with a Row_Number() partitioned by the LastName, and sorted by the FirstName.

    Here's the code

    ;WITH SecondTableWithDistinctLastName AS
    (
            SELECT  *
            FROM    (
                        SELECT  *,
                                ROW_NUMBER() OVER (PARTITION BY LastName ORDER BY FirstName) AS [Rank]
                        FROM    AddTbl
                    )   
            AS      tableWithRank
            WHERE   tableWithRank.[Rank] = 1
    ) 
    SELECT          a.FirstName, a.LastName, S.District
    FROM            SecondTableWithDistinctLastName AS S
    INNER JOIN      AddTbl AS a
        ON          a.LastName = S.LastName
    ORDER   BY      a.FirstName
    

提交回复
热议问题