假设我有列A,B和日期,并且我希望删除A中重复的所有行,同时保留具有最新日期的行。我该怎么做?
我已经查看了许多其他解决方案,但似乎没有一个适用于我的情况。
提前感谢您提供任何帮助
答案 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
答案 1 :(得分: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)
当然不是比较你应该命名你的表