[英]Postgres: Get the Complement of Distinct Entries
目前,我可以從像這樣的表中獲得不同的條目:
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
不過要小心。 您正在使用不帶order by
子句的distinct on
。 數據中返回的特定行是不確定的。 您應在原始數據和此處的子查詢中添加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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.