2014-01-30 80 views
0
CREATE TABLE #A (Type Char(20),ID INT, ID2 int,Address VARCHAR(10)) 
INSERT INTO #A (Type,ID, ID2,Address) 
VALUES ('Child',101,290,'CAT'), 
     ('Child',102,290,'CAR'), 
     ('Self',290,290,'CAT') 
     ,('Spouse',103, 777,'DOE') 
     ,('Self',777,777,'DOE') 
     ,('Self',811,NULL,'yyy') 

因此,在#A中ID是唯一的,ID2是分組,因此,記錄1-3在一個組中是4-5,依此類推。 我想顯示所有的「ID」,其中 (i)對於每個組,如果地址對於所有記錄都是相同的,我想獲得ID其中type ='self' (ii)如果每個組的地址是對於少數記錄不同,我想獲得self的ID和其他地址不同的recod的ID。 (iii)如果不存在組,即ID2爲空,我需要記錄的ID。選擇記錄組由

所以,輸出應該是

102 
290 
777 
811 

消除ID 101,因爲290具有相同的地址和它們屬於相同的組。 保持290,因爲它是自我。

謝謝!

回答

1

爲了解決這類問題,我發現將條件轉換成每行的標記/度量值是很有用的。窗口函數對此非常有用。

下實現了三個規則:

select type, id, id2, address 
from (select a.*, 
      rank() over (partition by id2 order by AddressCnt desc) as AddressRank 
     from (select a.*, 
        (case when max(address) over (partition by id2) = 
           min(address) over (partition by id2) 
         then 1 else 0 
        end) as AddressSame, 
        count(*) over (partition by id2, Address) as AddressCnt 
      from a 
      ) a 
    ) a 
where (AddressSame = 1 and type = 'self') or 
     (AddressRank > 1 or type = 'self') or 
     id2 is null; 

的SQL小提琴是here