Left Table full and right table data if exists

kasim mohamed 581 Reputation points
2021-12-28T11:00:43.573+00:00

Hi
I have two table like below

create table ##tab1 (AccNo nvarchar(10), tab1InvNo nvarchar(10), tab1Qty int)
create table ##tab2 (AccNo nvarchar(10), tab2InvNo nvarchar(10), tab2Qty int)
create table ##Result (AccNo nvarchar(10), tab1InvNo nvarchar(10), tab1Qty int, tab2InvNo nvarchar(10), tab2Qty int)
insert into ##tab1 values (1001, 2001, 1)
insert into ##tab1 values (1001, 2002, 2)
insert into ##tab1 values (1001, 2003, 5)

insert into ##tab2 values (1001, 2001, 1)

select * from ##tab1
select * from ##tab2
160883-image.png

I need the result like below
Left table full data and right table data if exists

create table ##Result (AccNo nvarchar(10), tab1InvNo nvarchar(10), tab1Qty int, tab2InvNo nvarchar(10), tab2Qty int)
insert into ##Result values (1001,2001,1,2001,1)
insert into ##Result values (1001,2002,2,'',0)
insert into ##Result values (1001,2003,5,'',0)
select * from ##Result
160915-image.png

Thanks in Advance

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
SQL Server | Other
0 comments No comments
{count} votes

Answer accepted by question author
  1. Olaf Helper 47,586 Reputation points
    2021-12-28T11:07:56.073+00:00

    Try it with an OUTER JOIN and the ISNULL function, like

    SELECT T1.*, ISNULL(T2.tab2InvNo) AS tab2InvNo, ISNULL(T2.tab2Qty, 0) AS tab2Qty
    FROM ##tab1 AS T1
         LEFT JOIN
         ##tab2 AS T2
             ON T1.AccNo = T2.AccNo
                AND T1.tab1InvNo = T2.tab2InvNo
    
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

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