Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

sql server - Union on two tables based on a specific column

I have two tables which have many records , both table have few records where the id is same , I want to have unique group of rows where I have unique id from one particular table incase there are two same id in table

for example

enter image description here

In the above snippet we have empid 1 on both table so , I want all the records such that If there are common empid in both table then value for the common empid the value should be used from Dummy_tab_2 table .

Desired O/P

enter image description here

code to replicate


CREATE TABLE Dummy_tab_1
(
    empid int,
    Month1 int,
    Month2 int,
);
 
INSERT INTO Dummy_tab_1 
VALUES (1, 100, 200), (5,15, 20), (6, 20, 30);


CREATE TABLE Dummy_tab_2 
(
    empid int,
    Month1 int,
    Month2 int,
);
 
INSERT INTO Dummy_tab_2 
VALUES (1, 10, 20), (2,15, 20), (3, 20, 30);

I tried this but not sure how to remove the emp id which is not desired

SELECT *
FROM  Dummy_tab_2 
UNION
SELECT *
FROM   Dummy_tab_1

and o/p which I got is this

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using:

SELECT * FROM Dummy_tab_1 WHERE empid NOT IN (SELECT empid FROM Dummy_tab_2)
UNION ALL
SELECT * FROM Dummy_tab_2;

db<>fiddle demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...