SQL根据条件加入额外列

时间:2011-09-11 13:25:01

标签: sql-server tsql join

我想知道如何根据条件为Join添加额外的列。

我正在尝试做类似下面的大纲。如果一个地方是一个县,那么我想要县内的所有物业;但是,如果该位置是一个小镇,我想要该镇的房产。不幸的是,城镇代码可以跨县复制,所以我需要按县和城镇代码进行过滤。

SELECT DISTINCT [PropertyID] 
FROM PropertyLocations
LEFT JOIN [dbo].[Locations]
   ON [PropertyLocations].[CountyCode] = [Locations].[CountyCode]
 -- IF / CASE locations.[LocationLevel] is 6 then 
 -- i want to join on a second column as well
 -- [PropertyLocations].[CountySubCode] = [Locations].[SubCountyCode]
WHERE [LocationName] = 'county/town name'
AND [PropertyLocations].[CountyCode] = [Locations].[CountyCode]
order BY [PropertyID]

1 个答案:

答案 0 :(得分:4)

这是你需要的吗?

   LEFT JOIN [dbo].[Locations]
     ON [PropertyLocations].[CountyCode] = [Locations].[CountyCode]
        AND ( [Locations].[LocationLevel] <> 6
               OR [PropertyLocations].[CountySubCode] =
                  [Locations].[SubCountyCode]
            )