如果具有同一 ID 的任何记录满足两个条件,则排除该 ID 的所有记录

Excluding all records of the same ID if any record with that ID meets two conditions

我有一个 table 看起来像这样:

ID    Pet
01    Dog
01    Cat
01    Parrot
01    Guinea Pig
02    Dog
02    Guinea Pig
03    Parrot

如果一个 ID 有一只狗和一只猫,那么我想排除该 ID 的所有记录,无论它们还有什么其他动物。所以我的输出 table 看起来像:

ID    Pet
02    Dog
02    Guinea Pig
03    Parrot

这是我试过的查询:

PROC SQL;
CREAT TABLE new_table AS
SELECT * from Pets a
WHERE NOT EXISTS (SELECT *
                  FROM Pets b
                  WHERE b.ID = a.ID
                  AND b.ID = "Dog"
                  AND b.ID = "Guinea Cat"));
RUN;

这似乎没有用,实际上并没有过滤掉任何东西。

这就是你想要的:

SELECT
  * 
FROM
  pets 
WHERE
  id NOT IN
  (
    SELECT
      a.id 
    FROM
      pets a 
      JOIN
        pets b 
        ON a.id = b.id 
        AND a.pet = "Dog" 
        AND b.pet = "Cat"
  )

内部 SQL 查询正在查找同时存在 pet = "Dog" 行和 pet = "Cat" 行的 ID。外层 SQL 正在过滤掉那些 ID。

这在 PROC SQL 中很容易,因为 SAS 会自动将汇总统计信息重新合并回详细信息行。

data have;
  input ID $ Pet . ;
cards;
01    Dog
01    Cat
01    Parrot
01    Guinea Pig
02    Dog
02    Guinea Pig
03    Parrot
;

proc sql;
create table want as 
  select * 
  from have
  group by id
  having not (max(pet='Dog') and max(pet='Cat')) 
  order by id,pet
;
quit;