gpt4 book ai didi

database - Postgres : Is it possible to show only one entry when duplicate occurs?

转载 作者:搜寻专家 更新时间:2023-10-30 20:19:06 24 4
gpt4 key购买 nike

我有一个包含重复条目的 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

提前致谢

最佳答案

试试这个:

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 Fidle Demo

关于database - Postgres : Is it possible to show only one entry when duplicate occurs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15781452/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com