分区内的 Oracle SQL 顺序
Oracle SQL order within partition
我有一个视图,其中结果按序列的降序返回。结果集中的一列是 correlation_id ,这对于一堆行是相同的。我希望按照创建时间戳的顺序在 correlation_id 的分区内应用排序。
Data:
---------------------------
SEQ | CORRELATION_ID | CR_TIMESTAMP
9 | Z | 22/FEB/16 03:00:19.191000000 PM
8 | Z | 22/FEB/16 02:00:26.577000000 PM
7 | Z | 22/FEB/16 01:07:58.171000000 PM
6 | A | 22/FEB/16 03:07:58.171000000 PM
5 | A | 22/FEB/16 02:07:58.171000000 PM
What I want is maintain original order, only sort within the partition by CR_TIMESTAMP:
---------------------------
SEQ | CORRELATION_ID | CR_TIMESTAMP | SRLNO
7 | Z | 22/FEB/16 03:07:58.171000000 PM | 1
8 | Z | 22/FEB/16 02:00:26.577000000 PM | 2
9 | Z | 22/FEB/16 01:07:58.171000000 PM | 3
5 | A | 22/FEB/16 02:07:58.171000000 PM | 1
6 | A | 22/FEB/16 03:07:58.171000000 PM | 2
I tried (without success)
select V.*, ROW_NUMBER()
OVER (PARTITION BY CORRELATION_ID
ORDER BY CR_TIMESTAMP ASC) as SRLNO FROM A_VIEW V;
我的尝试结果为:最终结果按 CORRELATION_ID 的升序排列。即所有 A,然后所有 B,然后 .. 所有 Z。在每个分区内,排名正确地按 CR_TIMESTAMP 的顺序排列。
我是这样理解你的要求的:你首先要CORRELATION_ID
Z,因为它的最高SEQ
(9)高于A的最高SEQ
(6),但是里面每个 CORRELATION_ID
您希望按日期排序的记录。
select seq, correlation_id, cr_timestamp
from mytable
order by max(seq) over (partition by correlation_id) desc, cr_timestamp desc;
我有一个视图,其中结果按序列的降序返回。结果集中的一列是 correlation_id ,这对于一堆行是相同的。我希望按照创建时间戳的顺序在 correlation_id 的分区内应用排序。
Data: --------------------------- SEQ | CORRELATION_ID | CR_TIMESTAMP 9 | Z | 22/FEB/16 03:00:19.191000000 PM 8 | Z | 22/FEB/16 02:00:26.577000000 PM 7 | Z | 22/FEB/16 01:07:58.171000000 PM 6 | A | 22/FEB/16 03:07:58.171000000 PM 5 | A | 22/FEB/16 02:07:58.171000000 PM What I want is maintain original order, only sort within the partition by CR_TIMESTAMP: --------------------------- SEQ | CORRELATION_ID | CR_TIMESTAMP | SRLNO 7 | Z | 22/FEB/16 03:07:58.171000000 PM | 1 8 | Z | 22/FEB/16 02:00:26.577000000 PM | 2 9 | Z | 22/FEB/16 01:07:58.171000000 PM | 3 5 | A | 22/FEB/16 02:07:58.171000000 PM | 1 6 | A | 22/FEB/16 03:07:58.171000000 PM | 2 I tried (without success) select V.*, ROW_NUMBER() OVER (PARTITION BY CORRELATION_ID ORDER BY CR_TIMESTAMP ASC) as SRLNO FROM A_VIEW V;
我的尝试结果为:最终结果按 CORRELATION_ID 的升序排列。即所有 A,然后所有 B,然后 .. 所有 Z。在每个分区内,排名正确地按 CR_TIMESTAMP 的顺序排列。
我是这样理解你的要求的:你首先要CORRELATION_ID
Z,因为它的最高SEQ
(9)高于A的最高SEQ
(6),但是里面每个 CORRELATION_ID
您希望按日期排序的记录。
select seq, correlation_id, cr_timestamp
from mytable
order by max(seq) over (partition by correlation_id) desc, cr_timestamp desc;