2014-03-06 71 views
2

請參考下面的SQL結構:過濾一組記錄

CREATE table TestTable (id int not null identity, [type] char(1), groupid int) 

INSERT INTO TestTable ([type]) values ('a',1) 
INSERT INTO TestTable ([type]) values ('a',1) 
INSERT INTO TestTable ([type]) values ('b',1) 
INSERT INTO TestTable ([type]) values ('b',1) 
INSERT INTO TestTable ([type]) values ('a',2) 
INSERT INTO TestTable ([type]) values ('a',2) 

前四個記錄是第1組的一部分,並且所述第五和第六記錄是組2

的一部分。如果有在組中至少有一個b,那麼我希望查詢只返回該組的b。如果沒有b,那麼查詢應該返回該組的所有記錄。

回答

3

在這裏你去

SELECT * 
FROM testtable 
LEFT JOIN (SELECT distinct groupid FROM TestTable WHERE type = 'b' 
) blist ON blist.groupid = testtable.groupid 
WHERE (blist.groupid = testtable.groupid and type = 'b') OR 
     (blist.groupid is null) 

它是如何工作

  • 加入到所含的B項的列表。

  • 然後在where語句中...如果我們存在於那個列表中只需要b類型。否則,採取一切。


作爲後注意您可能是可愛與地方像這樣

WHERE ISNULL(blist.groupid,testtable.groupid) = testtable.groupid 

我覺得這是不太清楚條款 - 但往往是高級用戶將如何做到這一點。

+0

謝謝。這看起來不錯。加1,我會盡快測試。 – w0051977