根据列数据生成序列号

时间:2019-08-05 06:08:53

标签: sql oracle oracle11g

我有如下数据

    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; 

它将按顺序提供输出,而不是预期输出

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

2 个答案:

答案 0 :(得分:3)

您要根据The ASCII value of all control characters are 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 127 264 288 308 310 320 334 336 346 348 372 374 390 398 404 406 412 420 428 436 444 452 458 460 466 468 474 476 484 492 500 506 512 518 530 536 542 638 644 656 662 668 682 688 694 700 706 708 714 716 718 760 774 780 782 788 798 826 834 836 846 854 856 864 866 874 876 882 888 890 892 898 900 908 962 968 970 988 994 1000 中的顺序计算type中的更改次数:

transaction_id

子查询使用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; 确定先前的类型。外部查询仅计算其更改次数。

答案 1 :(得分:0)

您可以尝试

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