我有資料集:

我需要查看一個月內是否有與前 3 個月關閉的相同票種型別的票。
例如,如果我檢查 9 月關閉的票。從9月開始的3個月,包括9月是7月、8月、9月。9月有2張票3和4票。7月、8月和9月確實有3票和4票。因此,門票的重復編號為 2。
現在,讓我們看看八月。從 8 月開始的 3 個月,包括 8 月是 6 月、7 月和 8 月。在 8 月有 1 張票型別為 1。如果我們檢查在 6 月、7 月和 8 月關閉的票,確實有型別 1 的票。因此,重復票數為 1。
如果沒有相同票種的票,則重復票數應等于 0。

我假設我需要查看視窗函式,不是嗎?
我在https://chartio.com/learn/postgresql/how-to-create-a-rolling-period-running-total/找到了這篇文章,我覺得這是一個方向。這是對的嗎?
uj5u.com熱心網友回復:
你可以這樣做:
with cte as (
select distinct
date_part('month', t.closed_date) as month,
t.type
from test as t
)
select
c.month,
count(distinct c.type) as repeat_cnt
from cte as c
inner join cte as c2 on
c2.type = c.type and
c2.month between c.month - 3 and c.month - 1
group by
c.month;
輸出是:
7,2 -- July - 2 tickets
8,1 -- August - 1 ticket
9,2 -- September - 2 tickets
db小提琴示例
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/511373.html
標籤:PostgreSQL
上一篇:資料庫輸入問題。只寫入空值
