【问题标题】:numbering partitions based on changing dimensions根据变化的维度对分区进行编号
【发布时间】:2015-10-13 18:25:09
【问题描述】:

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

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

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

【问题讨论】:

  • 试试dense_rank() over (partition by customer,contract,type1,type2 order by customer, type1, type2) as partition
  • @vkp 为每一行分配数字 1

标签: sql oracle aggregation


【解决方案1】:

如果我理解正确,您需要相邻的行组,其中“相邻”基于 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;

【讨论】:

  • 这里描述的方法称为Tabibitosan方法。 BoneistRob Van WijkAketi Jyuuzou 都提供了关于该方法的好文章
  • @Jyuuzou 。 . .我很确定我在 25 年前的 Thinking Machines 日子里使用过类似的东西,那时分析功能还没有成为任何数据库的一部分。这些是利用并行扫描操作的技巧。
猜你喜欢
  • 2016-05-13
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
  • 1970-01-01
  • 2016-08-19
  • 2019-12-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多