Join in SQL with Duplicate Key

jn93 671 Reputation points
2022-11-22T06:38:33.323+00:00

Hi All, Lets say I have table like below. I do have the duplicate data as per shown below. When I joining using on QUOKEY, I didn't get the expected result like shown below. How can I get the expected result like below? This is part of my SSIS project.

SQL Version:
262951-image.png

Table:

262807-image.png

DDL and Sample Data Population:

   -- DDL and sample data population, start  
   DECLARE @tbl TABLE (QUOKEY varchar(50), VEHNO varchar(50), CLS varchar(50))  
   INSERT INTO @tbl (QUOKEY, VEHNO, CLS) VALUES  
   ('91TMIQUO5750161','WGE223','CA'),  
   ('91TMIQUO3338345','PKQ902','PC'),  
   ('91TMIQUO3338345','PKQ902','PC'),  
   ('91TMIQUO3660377','CCQ2927','PC'),  
   ('91TMIQUO3660377','CCQ2927','PC')  
  
      DECLARE @tbl2 TABLE (QUOKEY varchar(50), DT_UKEY varchar(50))  
   INSERT INTO @tbl2 (QUOKEY,DT_UKEY) VALUES  
   ('91TMIQUO5750161','9102413820220512151552306'),  
   ('91TMIQUO3338345','9102278620220517135729342'),  
   ('91TMIQUO3338345','9102278620220517135729342'),  
   ('91TMIQUO3660377','9102630020220527111614201'),  
   ('91TMIQUO3660377','9102630020220527111614201')  
  
   SELECT *  
  FROM @tbl a    
  INNER JOIN @tbl2 b ON a.QUOKEY=b.QUOKEY  
  
   -- DDL and sample data population, end  
SQL Server Integration Services
SQL Server Integration Services
A Microsoft platform for building enterprise-level data integration and data transformations solutions.
2,702 questions
Developer technologies Transact-SQL
0 comments No comments
{count} votes

Accepted answer
  1. LiHongMSFT-4306 31,566 Reputation points
    2022-11-22T06:59:08.307+00:00

    Hi @jn93
    Try this query:

    SELECT *  
    FROM @tbl a INNER JOIN (SELECT DISTINCT * FROM @tbl2) b ON a.QUOKEY=b.QUOKEY  
    

    Best regards,
    LiHong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. Viorel 122.5K Reputation points
    2022-11-22T06:48:40.467+00:00

    Check a query:

    ;   
    with A as  
    (  
        select *, row_number() over (partition by QUOKEY order by QUOKEY) as n  
        from @tbl  
    ),  
    B as  
    (  
        select *, row_number() over (partition by QUOKEY order by QUOKEY) as n  
        from @tbl2  
    )  
    select a.QUOKEY, a.VEHNO, a.CLS, b.DT_UKEY  
    from A  
    inner join B on B.QUOKEY = A.QUOKEY and B.n = A.n  
    order by A.CLS, A.QUOKEY  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.