0

假设我有下表 Person tablepersonStatus table.

declare @Persons table
(PersonId int)

insert into @Persons select 10   
insert into @Persons select 11    

declare @PersonStatus table
(id int,statuss int)

insert into @PersonStatus (id,statuss) values(10,0)
insert into @PersonStatus (id,statuss) values(10,0)
insert into @PersonStatus (id,statuss) values(11,1)
insert into @PersonStatus (id,statuss) values(10,0)
insert into @PersonStatus (id,statuss) values(11,0)

现在我想找到所有状态都为零的人员 ID 结果只是 ---> 10

怎么做?

4

3 回答 3

1
SELECT  id
FROM    @PersonStatus
GROUP   BY ID
HAVING  COUNT(DISTINCT statuss) = 1 AND
        MAX(statuss) = 0

或者

SELECT  id
FROM    @PersonStatus
GROUP   BY ID
HAVING  MAX(statuss) = MIN(statuss) AND
        MAX(statuss) = 0
于 2013-03-27T12:31:35.627 回答
1

由于我假设该@Persons表不仅仅是一PersonId列,而且您可能需要其他列,因此我认为@Persons需要成为查询的一部分。

SELECT p.PersonId --, other columns from p
 FROM @Persons AS p
 WHERE EXISTS (SELECT id FROM @PersonStatus
   WHERE id = p.PersonId
   GROUP BY id HAVING MAX(statuss) = 0);
于 2013-03-27T12:36:39.777 回答
0
select distinct p.id from @PersonStatus as p
where Statuss = 0
and not exists (select null from @Personstatus as t
                where p.id = t.id and t.statuss <> 0)
于 2013-03-27T12:32:27.577 回答