我有2个表,我希望case语句子查询将返回值字符串值“ Rural”(如果不匹配)设置为“ Urban”(如果为true)。我需要查询表2来查看城市名称是否存在。
当前,我的查询始终返回错误值'RURAL'
, CASE --This CASE is identifying Urban communities as listed in the contract, and leaving the rest as Rural.
WHEN t1.city in (select top 1 city from t1
left join t2 on t2.city2 = t1.city
where t2.city2 = t1.city
)
then 'Urban'
ELSE 'Rural'
end as URBAN_RURAL
select t1.city
, t2.city2
, CASE --This CASE is identifying Urban communities and leaving the rest as Rural.
WHEN Exists (select top 1 from t1 where t1.city = t2.city2)
then 'Urban'
ELSE 'Rural'
end as Urban_Status;
from t1 with (nolock)
left join t2 with (nolock)
on t1.city = t2.city
我想使用查找表,因为我们可能正在修改符合城市资格的内容,而只是从该表t2中添加或删除名称。因此,如果case语句可以返回Urban字符串值以匹配两个表中的结果,而Rural则返回不匹配项,那么将是理想的。
示例结果为
City City2 UrbanRural
Orono NULL Rural
Bangor Bangor Urban
Machias Null Rural
答案 0 :(得分:0)
我想这就是你想要的。但是如果没有样本预期结果,就不能确定。
SELECT COALESCE(
( SELECT 'URBAN'
FROM T2
WHERE T1.city = T2.city
), 'RURAL' ) AS CITY_TYPE,
T1.*
FROM T1
答案 1 :(得分:0)
如果您已经在t1
子句中加入了t2
和FROM
,则根本不需要内联子查询。
SELECT
CASE
WHEN t2.city(2?) IS NULL THEN 'URBAN'
ELSE 'RURAL'
END AS URBAN_RURAL
FROM t1
LEFT JOIN t2
ON t1.city = t2.city
注意:NOLOCK
已删除-如果您确实需要它,请放回去,但请参阅Bad habits : Putting NOLOCK everywhere