假设我有以下表格
Person table
和personStatus 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
怎么做?
答案 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)