嘗試獲取所有客戶的第二個交易月詳細資訊
Date User_id amount
2021-11-01 1 100
2021-11-21 1 200
2021-12-20 2 110
2022-01-20 2 200
2022-02-04 1 50
2022-02-21 1 100
2022-03-22 2 200
對于每個客戶,獲取他們第二次交易當月的所有記錄(特定用戶可以在一個月和一天內進行多次交易)
預期產出
Date User_id amount
2022-02-04 1 50
2022-02-21 1 100
2022-01-20 2 200
uj5u.com熱心網友回復:
您可以使用dense_rank:
select Date, User_id, amount from
(select *, dense_rank() over(partition by User_id order by year(Date), month(date)) r
from table_name) t
where r = 2;
小提琴
uj5u.com熱心網友回復:
如果dense_rank是一個選項,您可以:
with cte1 as (
select *, extract(year_month from date) as yyyymm
from t
), cte2 as (
select *, dense_rank() over (partition by user_id order by yyyymm) as dr
from cte1
)
select *
from cte2
where dr = 2
請注意,可以使用一個 cte 撰寫上述內容。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/436625.html
