我有一个带有重复条目的postgres数据库。我想显示created_by列和
id | name | created_on
1 | 'Hello' | 3/29
2 | 'Hey' | 4/3
3 | 'Hello' | 3/31
4 | 'Hey' | 4/1
由于'Hello'和'Hey'是重复的,我想形成一个查询列出以下内容:
id | name | created_on
2 | 'Hey' | 4/3
3 | 'Hello' | 3/31
我怎么能形成那个SQL查询?
实际上我尝试在单个查询中使用'DISTINCT ON'和'ORDER BY'(使用JOIN)它会给我以下错误:
SELECT DISTINCT ON expressions must match initial ORDER BY expressions
提前致谢
答案 0 :(得分:1)
试试这个:
SELECT t1.*
FROM tablename AS t1
INNER JOIN
(
SELECT name, MAX(created_on) AS MaxDate
FROM tablename
GROUP BY name
) AS t2 ON t1.name = t2.name
AND t1.created_on = t2.maxdate;
答案 1 :(得分:1)
尝试此查询
select
a.*
from
table1 a
inner join
(select
name,
max(created_on) as date
from
table1
group by
name)b
on
a.name = b.name AND
a.created_on = b.date
答案 2 :(得分:1)
select distinct on (name)
id, name, created_on
from tablename
order by name, created_on desc
如果您需要按ID订购:
select *
from (
select distinct on (name)
id, name, created_on
from tablename
order by name, created_on desc
) s
order by id