【问题标题】:Generate sequence numbers based on column data根据列数据生成序列号
【发布时间】:2019-08-05 20:17:26
【问题描述】:

我有如下数据

    Transaction_id, Type
    10001            PO
    10002            PO
    10003            PO
    10004            NON-PO
    10005            NON-PO
    10006            PO
    10007            PO
    10008            NON-PO
    10008            PO

我必须根据下面的输出生成序列或显示序列号

  Transaction_id, Type,    Sequence
  10001            PO        1
  10002            PO        1
  10003            PO        1
  10004            NON-PO    2
  10005            NON-PO    2
  10006            PO        3
  10007            PO        3
  10008            NON-PO    4
  10009            PO        5
create table test_data(Transaction_id NUMBER,"Type" Varchar2(100));

insert into test_data(Transaction_id,"Type") values(10001,'PO');
insert into test_data(Transaction_id,"Type") values(10002,'PO');
insert into test_data(Transaction_id,"Type") values(10003,'PO');
insert into test_data(Transaction_id,"Type") values(10004,'NON-PO');
insert into test_data(Transaction_id,"Type") values(10005,'NON-PO');
insert into test_data(Transaction_id,"Type") values(10006,'PO');
insert into test_data(Transaction_id,"Type") values(10007,'PO');
insert into test_data(Transaction_id,"Type") values(10008,'NON-PO');
insert into test_data(Transaction_id,"Type") values(10009,'PO');

commit;

数据插入到表中

序列创建:

create sequence seq_num start with 1 increment by 1; 

数据选择:

select Transaction_id,"Type",seq_num.nextval    
from test_data; 

它会按照序列而不是预期的输出给出输出

请建议如何实现请求的输出

【问题讨论】:

    标签: sql oracle oracle11g


    【解决方案1】:

    您想根据transaction_id 中的排序计算type 中的更改次数:

    select td.transaction_id, td."Type", 
           sum(case when prev_type = type then 0 else 1 end) over (order by transaction_id) 
           as "Sequence"
    from (select td.*,
                 lag("Type") over (order by transaction_id) as prev_type
          from test_data td
         ) td;
    

    子查询使用lag() 确定先前的类型。外部查询只是计算它改变的次数。

    【讨论】:

      【解决方案2】:

      你可以试试这个

       SELECT * , DENSE_RANK() OVER (ORDER BY type) AS SQUENCE FROM test_data
      

      【讨论】:

      • 我认为这行不通。您能创建示例数据并分享输出吗?
      猜你喜欢
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多