Postgres:获得不同作品的补充

时间:2013-06-12 19:55:10

标签: sql postgresql postgresql-9.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的不同集合的补充?

1 个答案:

答案 0 :(得分: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