繁体   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