2017-07-31 86 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'和'#'超級用戶 –

相關問題