Please assist with the query to find the extra records when creating table a and table b left join

ASHMITP 141 Reputation points
2022-05-24T22:43:53.447+00:00

Hi ,

Please assist with the query to find the extra records when creating table a and table b left join. table a and table b both have more than one records.
Here is the script -

select a.[Fac],convert(varchar,b.fac_id + '-' + RIGHT('0000000000'+CAST(b.MRN AS VARCHAR(10)),10),50)
,surname+', '+given_names as name
from table1 a
left join table2 b
on a.[Fac] =convert(varchar,b.fac_id + '-' + RIGHT('0000000000'+CAST(b.MRN AS VARCHAR(10)),10),50)
order by a.[Fac]

The first table giving me 3277186 records . but when doing left join getting 3277290 record. My request is how to see the 104 records which is extra. Can someone help me with the query ?

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,619 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,546 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Naomi 7,361 Reputation points
    2022-05-25T01:23:05.27+00:00

    Try as a possible query:

    ;with cte as (select a.[Fac],convert(varchar,b.fac_id + '-' + RIGHT('0000000000'+CAST(b.MRN AS VARCHAR(10)),10),50)
    ,surname+', '+given_names as name, count(*) over (partition by a.PK) as cntIds
    from table1 a
    left join table2 b
    on a.[Fac] =convert(varchar,b.fac_id + '-' + RIGHT('0000000000'+CAST(b.MRN AS VARCHAR(10)),10),50))
    
    select * from cte where cntIds > 1
    order by [Fac]
    
    0 comments No comments

  2. Bert Zhou-msft 3,421 Reputation points
    2022-05-25T02:30:56.9+00:00

    Hi,@ASHMITP

    Welcome to Microsoft T-SQL Q&A Forum!

    Not tested, but you might try:

    select *  
    From  table2  
    where not exists(  
    select  table1.[Fac]  
    from   table1  
    where table1.[Fac]=convert(varchar,table2.fac_id + '-' + RIGHT('0000000000'+CAST(table2.MRN AS VARCHAR(10)),10),50)  
      
    )  
    

    Best regards,
    Bert Zhou


    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.

    0 comments No comments