2011-09-11 72 views
1

我想知道如何根據條件向連接添加額外的列。基於條件的SQL連接額外列

我正在嘗試做下面的大綱。如果一個地點是一個縣,那麼我想要縣裏的所有房產;然而,如果位置是一個城鎮,我想要那個城鎮的房產。不幸的是,城鎮代碼可以跨縣複製,所以我需要按縣和城鎮代碼進行過濾。

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] 

回答

4

這是你所需要的?

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

感謝馬丁這正是我需要的。 – Dave

+0

@Martin:這種方法會有什麼性能問題嗎?特別是如果記錄數量更多。 – Novice