1

目前我可以从这样的表中获得不同的条目:

SELECT DISTINCT ON (abc.entry) abc.* FROM table abc
    JOIN table1 def ON abc.entry = def.entry
WHERE def.created >= 'some_date' AND def.position = 1;

有没有办法获取每个具有重复项的条目(即在 some_date 上的不同集的补集?

4

1 回答 1

2

您可以使用having子句来获取重复条目的列表:

SELECT abc.entry
FROM table abc JOIN
     table1 def
     ON abc.entry = def.entry
WHERE def.created >= 'some_date' AND def.position = 1
group by abc.entry
having count(*) > 1

要获取行列表,我会使用窗口函数:

select t.*
from (SELECT abc.*, count(*) over (partition by entry) as cnt
      FROM table abc JOIN
           table1 def
           ON abc.entry = def.entry
      WHERE def.created >= 'some_date' AND def.position = 1
     ) t
where cnt > 1;

编辑:

我看到了术语的混乱。 DISTINCT在 SQL 中具有非常特殊的含义。而且,DISTINCT ON在 Postgres 中具有相当不同的含义。我认为您必须使用子查询来执行此操作:

select abc.*
from table abc left outer join
     (SELECT DISTINCT ON (abc.entry) abc.* FROM table abc
      JOIN table1 def ON abc.entry = def.entry
      WHERE def.created >= 'some_date' AND def.position = 1
     ) f
     on abc.id = f.id
where f.id is NULL

不过,请注意。您正在使用distinct on没有order by子句。数据中返回的特定行是不确定的。您应该order by在此处向原始数据和子查询添加一个。

select abc.*
from table abc left outer join
     (SELECT abc.entry, max(abc.id) as maxid
      FROM table abc
      JOIN table1 def ON abc.entry = def.entry
      WHERE def.created >= 'some_date' AND def.position = 1
      group by abc.entry
     ) f
     on abc.id = f.maxid
where f.maxid is NULL
于 2013-06-12T20:00:39.217 回答