根据重复发生的事件形成一系列操作

ha5z0ras  于 2022-09-18  发布在  Java
关注(0)|答案(1)|浏览(157)

我有一张table,看起来像这样:

ID          TARGET_ACTION              TARGET_DATE 

366                    0                21.04.2021      
186                    1                03.04.2021
929                    0                14.04.2021
366                    1                17.04.2021

此表中的每个ID可以重复,并且对于不同的日期具有不同的TARGET_ACTION值。我想为每个id形成一个操作序列,将其分成几周,使其看起来如下所示:

ID          01.04.2021-07.04.2021    08.04.2021-14.04.2021   15.04.2021-21.04.2021 

366                    0                       0                       1
186                    1                       1                       0
929                    0                       1                       0

我怎么能做到这一点?

nqwrtyyt

nqwrtyyt1#

在这种情况下,您可以使用旋转,尽管全年将有52周的列。首先,您的样本数据:

WITH
    a_table AS
        (
            Select 366  "ID",   0 "TARGET_ACTION",  To_Date('21.04.2021', 'dd.mm.yyyy') "TARGET_DATE" From Dual Union All
            Select 186  "ID",   1 "TARGET_ACTION",  To_Date('03.04.2021', 'dd.mm.yyyy') "TARGET_DATE" From Dual Union All
            Select 929  "ID",   0 "TARGET_ACTION",  To_Date('14.04.2021', 'dd.mm.yyyy') "TARGET_DATE" From Dual Union All
            Select 366  "ID",   1 "TARGET_ACTION",  To_Date('17.04.2021', 'dd.mm.yyyy') "TARGET_DATE" From DUAL
        ),

接下来要做的是将您的数据集与某种时间维度表连接起来。这是一件非常好的事情,有不同的用途。指向如何创建的链接在此:http://oracleolap.blogspot.com/2011/01/script-for-time-dimension-table.html
相反,我创建了一个小型CTE,距离问题只有几周的时间:

weeks AS
    (
        SELECT 14 "WEEK_NUM", To_Date('01.04.2021', 'dd.mm.yyyy') "WEEK_STARTS", To_Date('07.04.2021', 'dd.mm.yyyy') "WEEK_ENDS" From Dual Union All
        SELECT 15 "WEEK_NUM", To_Date('08.04.2021', 'dd.mm.yyyy') "WEEK_STARTS", To_Date('14.04.2021', 'dd.mm.yyyy') "WEEK_ENDS" From Dual Union All
        SELECT 16 "WEEK_NUM", To_Date('15.04.2021', 'dd.mm.yyyy') "WEEK_STARTS", To_Date('21.04.2021', 'dd.mm.yyyy') "WEEK_ENDS" From Dual 
    )

现在,如果您从数据中获取周,并将它们与时间维连接起来,您就可以透视结果数据集。下面是带有结果的主SQL。

SELECT DISTINCT
    ID, W14, W15, W16
FROM
    (
        SELECT
            t.ID "ID",
            t.TARGET_ACTION "TARGET_ACTION",
            To_Char(t.TARGET_DATE, 'WW') "WEEK_NUM",
            w.WEEK_STARTS "WEEK_STARTS", 
            w.WEEK_ENDS "WEEK_ENDS"
        FROM
            a_table t
        INNER JOIN
            weeks w ON(To_Char(w.WEEK_NUM) = To_Char(t.TARGET_DATE, 'WW'))
    )
PIVOT
    (
        Count(WEEK_NUM)
        FOR WEEK_NUM IN(14 "W14", 15 "W15", 16 "W16")
    )
--  
--  R e s u l t
--  
--          ID        W14        W15        W16
--  ---------- ---------- ---------- ----------
--         929          0          1          0 
--         366          0          0          1 
--         186          1          0          0

致敬..。

相关问题