通过检查任何值是否与查找表匹配来设置状态?

时间:2017-09-06 19:40:11

标签: sql sql-server left-join

我有2个表Test1和Test2。如果M_OFF,M_PREF,R_OFF,R_PREF的任何1值与Test2表的CODE列中的值匹配,则将状态设置为'是',否则设置'否'

测试1:

ID | M_OFF | M_PREF | R_OFF | R_PREF
1  | H     | H      | M     | M
2  | H     | H      | L     | L
3  | L     | L      | L     | L

测试2:

CODE

H
M

预期输出:

ID | M_OFF | M_PREF | R_OFF | R_PREF | STATUS
1  | H     | H      | M     | M      | YES
2  | H     | H      | L     | L      | YES
3  | L     | L      | L     | L      | NO

加入两个表都会给我重复的值,这是不期望的。怎么做到这一点?

2 个答案:

答案 0 :(得分:2)

嗯。嗯。 。

select t1.*,
       (case when exists (select 1 from test2 t2 where t2.code in (t1.M_OFF, t1.M_PREF, t1.R_OFF, t1.R_PREF)
             then 'YES'
             else 'NO'
        end) as status
from test1 t1;

答案 1 :(得分:1)

您可以使用子查询:

SELECT ID, M_OFF, M_PREF, R_OFF, R_PREF, 
       CASE WHEN EXISTS (
           SELECT 1
           FROM Test2
           WHERE Code IN (M_OFF, M_PREF, R_OFF, R_PREF)
       ) THEN 'Yes'
       ELSE 'No'
       END As [Status]
FROM Test1