Oracle:按日期对子组的结果按相同日期排序

时间:2018-06-18 11:30:19

标签: oracle sorting date sql-order-by

我需要按照下面的创建日期列对我的整体结果进行排序,但是按照应用程序ID将它们组合在一起,这些子组按照相同的日期排序:

APPLICATION_ID  STATUS  CREATE_DATE
12345           REC     01-06-2017
12345           PRO     02-06-2017
12345           DEL     03-06-2017
12746           REC     02-06-2017
12746           REC     05-06-2017
12743           DEL     04-06-2017
12743           PRO     09-06-2017
12743           PRO     11-06-2017

APPLICATION_ID是数据类型VARCHAR2,CREATE_DATE是DATE类型。这两列都不可为空。

我无法访问架构中的其他相关表,我只能查询这个。 使用以下查询排序并不会给出我需要的整体日期顺序。

SELECT * FROM MY_TABLE ORDER BY APPLICATION_ID, CREATE_DATE;

示例输出:

APPLICATION_ID  STATUS  CREATE_DATE
10603           REC     15-06-2017
10603           PRO     15-06-2017
10603           DEL     22-06-2017
11251           REC     21-06-2017
11251           REC     21-06-2017
11894           DEL     02-06-2017
11894           PRO     05-06-2017
11894           PRO     06-06-2017

在上面,我试图让订单首先是11894记录,然后是10603,然后是11251

1 个答案:

答案 0 :(得分:0)

如果您想按应用程序最低订购创建日期,请考虑以下事项:

with MY_TABLE as (
  select 12746 APPLICATION_ID, 'REC' STATUS, date '2017-06-02' CREATE_DATE from dual union all
  select 12746 APPLICATION_ID, 'REC' STATUS, date '2017-06-05' CREATE_DATE from dual union all
  select 12743 APPLICATION_ID, 'DEL' STATUS, date '2017-06-04' CREATE_DATE from dual union all
  select 12743 APPLICATION_ID, 'PRO' STATUS, date '2017-06-09' CREATE_DATE from dual union all
  select 12743 APPLICATION_ID, 'PRO' STATUS, date '2017-06-11' CREATE_DATE from dual union all
  select 12345 APPLICATION_ID, 'REC' STATUS, date '2017-06-01' CREATE_DATE from dual union all
  select 12345 APPLICATION_ID, 'PRO' STATUS, date '2017-06-02' CREATE_DATE from dual union all
  select 12345 APPLICATION_ID, 'DEL' STATUS, date '2017-06-03' CREATE_DATE from dual
)
select *
from   MY_TABLE 
order by min(create_date) over(partition by APPLICATION_ID), APPLICATION_ID, CREATE_DATE

它会创建您列出的输出。