简体   繁体   中英

Merge two tables by two variables in SQL Server

I have two tables that I want to merge by the two common variables.

So I have Table1

Var1       Var2       Dates      
---------- ---------- ----------------------
111111     AA          1990-06-20
111111     AA          2000-06-20
222222     BB          1963-06-20
222222     BB          2005-06-20
333333     CC          2006-06-30
333333     CC          2016-06-26

and Table2

Var2       Dates      
---------- ----------------------
AA          1990-06-20
BB          1963-06-20

I want the output to be

Var1       Var2       Dates      
---------- ---------- ----------------------
111111     AA          1990-06-20
222222     BB          1963-06-20

I have tried inner join two times using "Var2" and "Dates" in two tables. But the results gave me more rows (duplicate entries) than I need.

Well, the most common way would be to use an INNER JOIN :

SELECT T1.*
FROM Table1 T1
INNER JOIN Table2 T2
    ON T1.Var1 = T2.Var1
    AND T1.Dates = T2.Dates

But this makes more sense when you also want to use some columns from the second table. In your case, you could do just:

SELECT *
FROM Table1 T1
WHERE EXISTS(SELECT 1 FROM Table2
             WHERE Var1 = T1.Var1
             AND Dates = T1.Dates)

I think in your case you need only one JOIN with multiple conditions

SELECT t1.*
FROM Table1 t1
    JOIN Table2 t2 ON t1.Var2 = t2.Var2 AND t1.Dates = t2.Dates

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM