简体   繁体   English

滚动期重复发病 - postgresql

[英]Rolling period repeat incidence - postgresql

I have the dataset:我有数据集:

在此处输入图像描述

I need to see whether there are tickets in a month with the same ticket type that were closed during the previous 3 months.我需要查看一个月内是否有与前 3 个月关闭的相同票证类型的票证。

For example, if I check the Sept closed tickets.例如,如果我检查 9 月关闭的票。 3 months from September, incl September are Jul, Aug, Sept. There were 2 tickets in Sept with ticket type 3 and ticket type 4. During Jul, Aug, and Sept, there were indeed tickets with ticket type 3 and 4. Hence, the repeat # of tickets is 2.从9月算起3个月,包括9月就是7月、8月、9月。9月有2张3号票和4号票。7月、8月、9月确实有3号票和4号票。因此,门票的重复次数为 2。

Now, let's look at August.现在,让我们看看八月。 3 months from August, inc August are Jun, Jul, and Aug. There was 1 ticket closed in August with ticket type 1. If we check tickets closed in June, Jul and Aug, there are indeed tickets with type 1. Hence, the repeat # of tickets is 1.从 8 月开始的 3 个月,包括 8 月是 6 月、7 月和 8 月。8 月有 1 张票关闭,票类型为 1。如果我们检查在 6 月、7 月和 8 月关闭的票,确实有类型 1 的票。因此,重复# of tickets 是 1。

If there were no tickets with the same ticket type, the repeat # of tickets should be equal to 0.如果没有相同票证类型的票证,则票证的重复# 应等于 0。

在此处输入图像描述

I assume I need to look into the window functions, don't I?我假设我需要查看 window 函数,不是吗?

I found the article at https://chartio.com/learn/postgresql/how-to-create-a-rolling-period-running-total/ and I feel it is a direction to go. Is it correct?我在https://chartio.com/learn/postgresql/how-to-create-a-rolling-period-running-total/找到这篇文章,我觉得它是指向 go 的方向。它是否正确?

You can do something like this:你可以这样做:

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;

the output is: output 是:

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

db fiddle example数据库小提琴示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM