如何检索包含和排除特定键的列表?

时间:2017-06-29 15:51:32

标签: sql teradata

我有一个这样的表,我需要过滤密钥并检索密钥列表。

id key
1   1
1   2
1   3
1   4
2   1
2   3
3   1
3   4
4   1
4   4

期望的输出:

id key
2   1
2   3
3   1
3   4

这里我想得到一个id列表,即(2,3),其中键1存在且键2丢失。

2 个答案:

答案 0 :(得分:1)

这回答了问题"这里我想得到一个id列表。 。 。其中键1存在且键2丢失。"

您可以使用existsnot exists

select t.*
from t
where exists (select 1 from t t2 where t2.id = t.id and t2.key = 1) and
      not exists (select 1 from t t2 where t2.id = t.id and t2.key = 2);

如果您只是想要ID,那么我更喜欢聚合和having

select id
from t
group by id
having sum(case when key = 1 then 1 else 0 end) > 0 and
       sum(case when key = 2 then 1 else 0 end) = 0;

答案 1 :(得分:0)

假设您的表名是'testing',那么根据您提到的输出,sql查询将是

SELECT * 来自testing WHERE key!= 2和id in(2,3)