根据变化的维度对分区进行编号

numbering partitions based on changing dimensions

我在为我的数据创建正确的分区时遇到了一些问题。这是我的数据的示例,包含所需的输出:

customer   contract   type1   type2   partition
100        1          A       A       1
100        2          A       A       1
100        3          A       B       2
100        4          A       B       2
100        5          A       B       2
100        6          A       A       3
100        7          A       A       3
100        8          C       A       4
100        9          C       A       4

我要构建的变量是最后一个,称为分区。我现在遇到的问题是,当使用 dense_rank 时,合同 1 和 2 与合同 6 和 7 组合在一起:

select
  t1.*
, dense_rank() over (order by customer, type1, type2) as partition
from table1 t1

我可以使用什么来生成所需的输出(在相当大的数据集上)?

如果我没理解错的话,你需要相邻的行组,其中 "adjacent" 基于 contract.

您可以使用 row_number() 值的差异来执行此操作。当值相邻时,这种差异是恒定的。结果提供了一个额外的分组列,提供您需要的信息:

select t1.*,
       dense_rank() over (order by customer, type1, type2, grp) as partition
from (select t1.*,
             (row_number() over (partition by customer order by contract) -
              row_number() over (partition by customer, type1, type2 order by contract)
             ) as grp
      from table1 t1
     ) t1;