簡體   English   中英

滾動期重復發病 - postgresql

[英]Rolling period repeat incidence - postgresql

我有數據集:

在此處輸入圖像描述

我需要查看一個月內是否有與前 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 的票。因此,重復# of tickets 是 1。

如果沒有相同票證類型的票證,則票證的重復# 應等於 0。

在此處輸入圖像描述

我假設我需要查看 window 函數,不是嗎?

我在https://chartio.com/learn/postgresql/how-to-create-a-rolling-period-running-total/找到這篇文章,我覺得它是指向 go 的方向。它是否正確?

你可以這樣做:

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;

output 是:

7,2 -- July - 2 tickets
8,1 -- August - 1 ticket
9,2 -- September - 2 tickets

數據庫小提琴示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM