sql—当数据大于同一类别的其他值时,如何划分行

yks3o0rb  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(358)

我使用row number()over(partition by)来获取客户购买产品时第一次发生的事件的数字索引。
使用sql查询:

SELECT

ROW_NUMBER () OVER (PARTITION BY
[Customer Name]
ORDER BY
[Created Date] ) AS Partition,

[Customer Name],

[Created Date]

FROM Database

我的数据填充如下:
当前表格

我的问题
我想我的数据分区额外的日期。但前提是下一天比前一天晚60天。数字列表将每60天重置一次。此表的填充方式如下:
理想数据

w1jd8yoj

w1jd8yoj1#

使用 lag() 以及定义组的累积和:

select t.*,
       sum(case when prev_createddate > dateadd(day, -60, createddate) then 0 else 1 end) over  (partition by customername order by createddate) as grp
from (select t.*,
             lag(createddate) over (partition by customername order by createddate) as prev_createddate
      from t
     ) t;

然后使用 row_number() 每组内:

select t.*,
       row_number() over (partition by customername, grp order by createddate) as mypartition
from (select t.*,
             sum(case when prev_createddate > dateadd(day, -60, createddate) then 0 else 1 end) over  (partition by customername order by createddate) as grp
      from (select t.*,
                   lag(createddate) over (partition by customername order by createddate) as prev_createddate
            from t
           ) t
     ) t;

请注意 partition 是一个非常糟糕的列名称,因为它是一个sql关键字。

相关问题