2017-07-31 85 views
0

假设我有列A,B和日期,并且希望删除在A中重复的所有行,同时保留具有最近日期的那一行。我将如何做到这一点?如何根据postgreSQL中的一列删除重复的行?

我看过很多其他解决方案,但似乎没有为我的情况。

预先感谢任何帮助

+0

请给出一些数据样本和预期结果 –

回答

0

这应该为你工作:

DELETE FROM YourTable USING 
    (SELECT colA, MAX(Date) maxDate 
    FROM YourTable 
    GROUP BY colA 
) AS Keep 
WHERE Keep.maxDate <> YourTable.Date 
AND Keep.ColA = YourTable.ColA 
0

会留:

t=# with sample(a,b,dat) as (values(1,1,1),(1,1,2),(1,2,3),(2,2,3),(2,2,4)) 
, comparison as (select *,max(dat) over (partition by a) from sample) 
select * 
from comparison 
where dat = max; 
a | b | dat | max 
---+---+-----+----- 
1 | 2 | 3 | 3 
2 | 2 | 4 | 4 
(2 rows) 

,从而被删除:

t=# with sample(a,b,dat) as (values(1,1,1),(1,1,2),(1,2,3),(2,2,3),(2,2,4)) 
, comparison as (select *,max(dat) over (partition by a) from sample) 
delete 
from comparison 
where dat <> max 
returning *; 
a | b | dat | max 
---+---+-----+----- 
1 | 1 | 1 | 3 
1 | 1 | 2 | 3 
2 | 2 | 3 | 4 
(3 rows) 

当然而不是比较你应该给你的表命名

+0

谢谢你的回答,一个问题,“t =#”是什么意思? – Nodeocrat

+0

https://www.postgresql.org/docs/current/static/app-psql.html#APP-PSQL-PROMPTING它是一个数据库名称't'和'#'超级用户 –

相关问题