我有一个如下表(使用 SQL Server 2008 R2):
CREATE TABLE [dbo].[Data](
    [Id] [int] NOT NULL,
    [Name] [nvarchar](100) NOT NULL,
    [IsBad] [bit] NOT NULL
) ON [PRIMARY]
GO
Insert into Data  values(100,'Book!',1)
Insert into Data  values(100,'Booklki**',1)
Insert into Data  values(100,'Book',0)
Insert into Data  values(100,'New Book ~~',1)
Insert into Data  values(100,'New Book',0)
Insert into Data  values(100,'B00k…>',1)
Insert into Data  values(101,'Tim3#',1)
Insert into Data  values(101,'%Timer%',1)
Insert into Data  values(101,'T1mer**',1)
Insert into Data  values(101,'Tim6',1)
Insert into Data  values(101,'Time@me',1)
Insert into Data  values(102,'ABC',0)
Insert into Data  values(102,'CDE',0)
我需要选择所有ID拥有的所有IsBad = 1. 因此,查询上表将返回 ID: 101。它不能返回102或100因为这些 ID 至少有一个IsBad=0.
我试过下面的查询
select id,count(distinct isBad) as Total
from Data
group by id
having count(distinct isBad)= 1 
此查询包括所有IsBad=0. 但我不需要那个。having我尝试在using 子句中添加更多条件AND,但出现错误。
如何进行 ?任何帮助表示赞赏。
编辑:我需要对有 5000 万条记录的表运行查询。因此,需要优化查询以在更短的时间内返回结果。