目前我可以从这样的表中获得不同的条目:
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的不同集合的补充?
答案 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