想象一下資料:
id audit_id val updated_at
1 11 43 October 09, 2021, 07:55 AM
1 12 34 October 11, 2021, 11:03 PM
1 13 88 January 23, 2022, 01:03 AM
1 14 34 January 23, 2022, 09:41 AM
2 21 200 June 28, 2021, 08:07 PM
2 22 200 December 23, 2021, 03:20 PM
2 23 205 January 12, 2022, 10:15 AM
2 24 211 May 13, 2022, 04:02 AM
每個 id,我想回傳兩個不同日期的最新條目(不僅僅是時間戳,日期部分應該不同):
id audit_id val updated_at
1 12 34 October 11, 2021, 11:03 PM
1 14 34 January 23, 2022, 09:41 AM
2 23 205 January 12, 2022, 10:15 AM
2 24 211 May 13, 2022, 04:02 AM
我假設我需要在 audit_id 上使用磁區和滯后,但我不知道如何開始構建它。
uj5u.com熱心網友回復:
我將分兩部分對此進行攻擊。第一個將確保僅保留單個日期的最新資訊。第二個編號從最新開始的行。
with by_day as (
select *,
updated_at::date !=
lag(updated_at::date) over (partition by id
order by updated_at desc) keep
from imagined_data
), numbered as (
select *, row_number() over (partition by id
order by updated_at desc) as rn
from by_day
where coalesce(keep, true)
)
select id, audit_id, val, updated_at
from numbered
where rn <= 2;
db<>在這里擺弄
uj5u.com熱心網友回復:
每組相同 id 的行編號,使最后兩個時間戳獲得編號 1 和 2,然后僅選擇它們。
select x.id, x.audit_id, x.val, x.updated_at
from (
select t.id, t.audit_id, t.val, t.updated_at
, row_number() over (partition by t.id order by t.updated_at desc) as rn
from your_table t
) x
where x.rn <= 2
order by x.id asc, x.updated_at asc
警告:我在腦海中撰寫它,沒有嘗試過。此外,如果您的updated_at列是實際文本,則需要對其進行轉換-我假設它是時間戳型別,并且您問題中的詳細格式只是(不是很實用)演示文稿。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/492073.html
標籤:sql PostgreSQL 日期
