Query required

dinesh 41 Reputation points
2021-07-21T06:58:42.643+00:00

Hi, I have two tables - Table1, Table2 . We can join these tables based on ID. In table1will have latest data and if it is having pop values then i have to get those values else i have to get cid values from table2.

create table1 (id varchar(10), popcid1 int,popcid2 int,popcid3 int)
create table2 (id varchar(10), cid1 int,cid2 int,cid3 int)

insert into table1(id,popcid1,popcid2,popcid3)
select 1,3,4,6
union
select 2,3,4,7
union
select 3,3,4,8

insert into table2(id,cid1,cid2,cid3)
select 3,3,4,5
union
select 4,13,14,15
union
select 5,11,14,15

output

id, popcid1,popcid2,popcid3
1,3,4,6
2,3,4,7
3,3,4,8
4,13,14,15
5,11,14,15

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

2 answers

Sort by: Most helpful
  1. EchoLiu-MSFT 14,581 Reputation points
    2021-07-21T07:10:30.387+00:00

    Please try:

    select * from table1  
    union   
    select * from table2  
    where id not in(select id from table1)  
    

    Or:

    select * from table1  
    union   
    select * from table2  
    where id not in(select id from table1  
                    where popcid1 is not null or  
     popcid2 is not null or  
     popcid3 is not null)  
    

    Output:
    116615-image.png

    If you have any question, please feel free to let me know.

    Regards
    Echo


    If the answer is helpful, please click "Accept Answer" and upvote it.

    0 comments No comments

  2. Guoxiong 8,206 Reputation points
    2021-07-21T14:04:37.513+00:00

    It seems you want to insert data to table1 if id does not exist in the table1 table. You can use the MERGE statement:

    MERGE table1 AS t  
    USING table2 AS s  
    	ON t.id = s.id  
    WHEN NOT MATCHED THEN  
    	INSERT (  
    		popcid1,  
    		popcid2,  
    		popcid3  
    	)  
    	VALUES (  
    		s.cid1,  
    		s.cid2,  
    		s.cid3  
    	);  
    
     
    
    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.