如何选择所有状态为零的记录?

时间:2013-03-27 12:28:53

标签: sql-server sql-server-2008 sql-server-2005 sql-server-2000

假设我有以下表格 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

怎么做?

3 个答案:

答案 0 :(得分:1)

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

OR

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

答案 1 :(得分: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);

答案 2 :(得分: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)