我正在使用 Postgres v12,并且我有一個包含重復行的表。我只需要檢索每個重復項的最后一個條目,忽略沒有重復項的條目。
此表具有以下列:
- id(唯一)
- request_id(在哪里可以找到重復項)
- created_at(在哪里查看哪個條目是最新的)
| ID | request_id | created_at |
|---|---|---|
| 1 | 一個 | 2020.06.06 |
| 2 | 一個 | 2020.05.05 |
| 3 | b | 2020.04.04 |
| 4 | b | 2020.03.03 |
| 5 | C | 2020.04.04 |
| 6 | C | 2020.03.03 |
| 7 | d | 2020.03.03 |
查詢應該檢索 id 為 1,3,5 的行,因為它們是每個副本的最新條目(created_at)。ID 7 沒有重復項,因此被忽略。
我已經嘗試過這里提出的解決方案:https ://www.geeksengine.com/article/get-single-record-from-duplicates.html但由于使用 Postgres v12,這些查詢不起作用,我得到了錯誤“列必須出現在 group by 子句中”這是這里參考的另一個問題:必須出現在 GROUP BY 子句中或用于聚合函式中
幾天來,我一直在尋找解決此問題的方法,但我不是 SQL 專家。我將非常感謝任何幫助。
uj5u.com熱心網友回復:
這是使用視窗函式的一種方法:
select * from (
select *
, row_number() over (partition by request_id order by created_at desc) as rn
, count() over (partition by request_id) cn
from tablename
) t where cn > 1 and rn = 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/491459.html
標籤:sql PostgreSQL
