Sql 如何仅返回ID不重复且另一列上有匹配值的行?

Sql 如何仅返回ID不重复且另一列上有匹配值的行?,sql,postgresql,Sql,Postgresql,我有一个表,需要在其中检查是否存在多个具有不同类型的ID,并返回只有一条记录且在type列中有试用版的ID 例如,使用此表: id|type -------- 12|trial 12|purchase 13|trial 14|purchase 14|trial 15|trial 我想返回以下结果: id|type -------- 13|trial 15|trial 因为他们只有一个记录包含一次试验。如果id包含试用和购买,我希望排除这些行。我认为您不希望存在: select t.* fro

我有一个表,需要在其中检查是否存在多个具有不同类型的ID,并返回只有一条记录且在type列中有试用版的ID

例如,使用此表:

id|type
--------
12|trial
12|purchase
13|trial
14|purchase
14|trial
15|trial
我想返回以下结果:

id|type
--------
13|trial
15|trial

因为他们只有一个记录包含一次试验。如果id包含试用和购买,我希望排除这些行。

我认为您不希望存在:

select t.*
from t
where t.type = 'trial' and
      not exists (select 1 from t t2 where t2.id = t.id and t2.type <> 'trial');

它可以通过使用内部查询来完成

select * from t where id IN (select id from t group by id having count(*) <= 1) AND trial = 'trial';

还有一种选择,使用联接。子查询将结果限制为唯一的id值,然后WHERE子句进一步筛选出您感兴趣的类型值

select 
  t.id,
  t.type
from
  @table as t
JOIN
  (
    select
      id
    from @table
    group by id
    having count(*)=1
  ) as d
    on d.id = t.id
where type = 'trial';

返回问题中的结果集。

不相关,但是:Postgres 9.1是您应该计划尽快升级到当前版本。我喜欢这些方法的简单性,但它们似乎不起作用,第二个没有t2或列名称trial@staten12 . . . 列名试验来自问题中的第二个表。我已经确定了答案。
select 
  t.id,
  t.type
from
  @table as t
JOIN
  (
    select
      id
    from @table
    group by id
    having count(*)=1
  ) as d
    on d.id = t.id
where type = 'trial';