暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Oracle 会话明智的排名,价值的变化应该会导致新的排名

ASKTOM 2020-07-10
424

问题描述

嗨,汤姆,

每当连续序列发生变化时,我需要帮助以获取序列no或秩以下是示例-
输入
seq,id,值
1、1,200
2、1,200
3、1,300
4、1,200
5、1,200
6、1,500
7、1,500
8、1,700

预期出相同的id组合,按顺序顺序的值应分配一个值。
对于id 1和值200-rnk应该为1,然后在第三行中发生变化-然后rnk = 2,然后应在第4行中分配新的rnk 3,而不是1,依此类推。

seq、id、值、rnk
1、1,200,1
2、1,200,1
3、1,300,2
4、1,200,3,
5、1,200,3,
6、1,500,4
7、1,500,4
8、1,700,5
9、1,800、6

我已经尝试了lead,lag,first_value,last_value,rank,dense_rank和row_number分析函数,但是我无法实现要求。

专家解答

因此,您想按SEQ对值进行排序,然后根据值更改时分配排名?

这是使用模式匹配 (match_regnize) 的一种方法

-按id划分,按seq排序
-将当前值 = prev (值) 的行组合在一起
-您希望将其用于任何行,然后是任意数量的行; 因此,这是 (init相同 *) 的模式
-使用match_number分配组号
-使用dense_rank中的此组编号分配等级

这给出了:

create table t (
  c1 int, c2 int, c3 int
);
insert into t values ( 1,1,200 );
insert into t values ( 2,1,200 );
insert into t values ( 3,1,300 );
insert into t values ( 4,1,200 );
insert into t values ( 5,1,200 );
insert into t values ( 6,1,500 );
insert into t values ( 7,1,500 );
insert into t values ( 8,1,700 );
commit;

select c1, c2, c3,
       dense_rank () over (
         partition by c2
         order by grp
       ) rk,
       grp
from   t
  match_recognize (
    partition by c2
    order by c1
    measures
      match_number() as grp
    all rows per match
    pattern ( init same* )
    define 
      same as c3 = prev ( c3 )
  );

C1    C2    C3     SEQ    GRP   
    1     1    200      1      1 
    2     1    200      1      1 
    3     1    300      2      2 
    4     1    200      3      3 
    5     1    200      3      3 
    6     1    500      4      4 
    7     1    500      4      4 
    8     1    700      5      5 


了解更多关于模式匹配的信息https://www.slideshare.net/ChrisSaxon1/how-to-find-patterns-in-your-data-with-sql
文章转载自ASKTOM,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论