请参阅下面的 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,则查询应返回该组的所有记录。
最佳答案
给你
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 子句来表现得更可爱
WHERE ISNULL(blist.groupid,testtable.groupid) = testtable.groupid
我认为这不太清楚——但高级用户通常会这样做。
关于sql - 过滤一组记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22231263/