[英]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 所以我有表1
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 和表2
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. 我在两个表中使用“ Var2”和“日期”两次尝试了内部联接。 But the results gave me more rows (duplicate entries) than I need.
但是结果给了我更多的行(重复的条目)。
Well, the most common way would be to use an INNER JOIN
: 好吧,最常见的方法是使用
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 我认为在您的情况下,您只需要一个具有多个条件的JOIN
SELECT t1.*
FROM Table1 t1
JOIN Table2 t2 ON t1.Var2 = t2.Var2 AND t1.Dates = t2.Dates
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.