目前我可以从这样的表中获得不同的条目:
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 上的不同集的补集?
目前我可以从这样的表中获得不同的条目:
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 上的不同集的补集?
您可以使用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