[英]Determine which keys should 2 tables use to Join in SQL Server
I have the follwoing 2 Tables: 我有以下两个表:
Table1: 表格1:
User-ID Country
1111 USA
2222 Brazil
3331 USA
3332 Korea
3333 Korea
3333 USA
3333 France
4444 UK
Table2: 表2:
User-ID Country Region
1111 USA NA
2222 Brazil SA
3331 Korea A
3332 Korea A
3333 N/A N/A
3330 France E
4444 UK E
I would like to join both table using the 'User-ID' as the common key with an exception. 我想使用'User-ID'作为公共键加入两个表,但有例外。
What I want the result to be like is that when the User-ID is '3333' I would like the 'Country' to be the common key instead ONLY. 我想要的结果是,当用户ID为“ 3333”时,我希望“国家/地区”成为公用密钥,而不是仅公用密钥。
I have tried the following ncode which sounded logical per my understanding but did not return the desitred result: 我尝试了以下按照我的理解听起来合理的ncode,但未返回期望的结果:
Select T1.User-ID, T1.Country, Case When T1.User-ID ='3333' AND T1.Country =
T2.Country THEN T2.Region ELSE T2.Region END
From Table1 as T1 Left Outer Join
Table2 as T2 ON T1.User-ID = T2.User-ID OR T1.Country = T2.Country
I have tried few other approaches buty with no succes, the results I will get will be the following: 我尝试了其他一些没有成功的方法,但是结果如下:
You seem to want an additional condition in the ON
clause: 您似乎在ON
子句中需要其他条件:
From Table1 T1 Left Outer Join
Table2 T2
ON T1.UserID = T2.UserID AND
(T1.UserId <> 33333 OR T1.Country = T2.Country)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.