Sql 筛选一组记录
请参见下面的SQL结构:Sql 筛选一组记录,sql,sql-server,Sql,Sql Server,请参见下面的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 TestTab
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)
前四条记录是第一组的一部分,第五和第六条记录是第二组的一部分
如果组中至少有一个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
我认为这一点不太清楚,但通常是高级用户将如何做到这一点