2

我有一个包含重复条目的 postgres 数据库。我想显示 created_by 列和

id | name    | created_on
1  | 'Hello' | 3/29
2  | 'Hey'   | 4/3
3  | 'Hello' | 3/31
4  | 'Hey'   | 4/1

由于“你好”和“嘿”是重复的,我想形成一个查询来列出以下内容:

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

提前致谢

4

3 回答 3

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;

SQL 文件演示

于 2013-04-03T07:40:59.717 回答
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

小提琴

于 2013-04-03T07:50:48.853 回答
1

SQL小提琴

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
于 2013-04-03T11:17:30.817 回答