[英]Add variable to count consecutive months
我在 Postgres 數據庫中有一個查詢,它結合了客戶端訂閱。
我想添加一個名為“連續幾個月”的變量,但我不確定如何在 Postgres 中執行此操作。
我的原始表是這樣的:
客戶 | 產品 | 日期 |
---|---|---|
1 | 子 | 2020-10-01 |
1 | 子 | 2020-11-01 |
2 | 子 | 2020-11-01 |
2 | 子 | 2020-12-01 |
1 | 子 | 2021-01-01 |
1 | 子 | 2021-02-01 |
2 | 子 | 2021-02-01 |
我希望有一些東西可以計算連續幾個月的起源,如下所示:
客戶 | 產品 | 日期 | 連續_月 |
---|---|---|---|
1 | 子 | 2020-10-01 | 1 |
1 | 子 | 2020-11-01 | 2 |
2 | 子 | 2020-11-01 | 1 |
2 | 子 | 2020-12-01 | 2 |
1 | 子 | 2021-01-01 | 1 |
1 | 子 | 2021-02-01 | 2 |
2 | 子 | 2021-02-01 | 1 |
感謝您對高級的幫助!
with A as (
select *,
date_part('year', dt) * 12 + date_part('month', dt)
- date_part('year', min(dt) over (partition by client, product)) * 12
- date_part('month', min(dt) over (partition by client, product)) + 1 as n,
row_number() over (partition by client, product order by dt) as rn
from T
)
select *,
row_number()
over (partition by client, product, n - rn order by dt) as consecutive_months
from A;
看起來你自己遇到了一個 Gaps-And-Islands 類型的問題。
訣竅是根據每個客戶端的連接日期計算一些排名。
然后可以根據客戶和排名計算一個序列號。
select client, product, "Date" , row_number() over (partition by client, daterank order by "Date") as Consecutive_months from ( select "Date", client, product , dense_rank() over (partition by client order by "Date") + (DATE_PART('year', AGE(current_date, "Date"))*12 + DATE_PART('month', AGE(current_date, "Date"))) daterank from raw t ) q order by "Date", client
\n客戶 | 產品 | 日期 | 連續_月\n -----: | :------ | :--------- | -----------------:\n 1 | 子 | 2020-10-01 | 1\n 1 | 子 | 2020-11-01 | 2\n 2 | 子 | 2020-11-01 | 1\n 2 | 子 | 2020-12-01 | 2\n 1 | 子 | 2021-01-01 | 1\n 1 | 子 | 2021-02-01 | 2\n 2 | 子 | 2021-02-01 | 1\n
db<> 在這里擺弄
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.