Sql &引用;“集团”;排序前将某些行合并在一起(Oracle)
我正在使用Oracle数据库11g。 我有一个从表中选择ID和日期的查询。基本上,我想做的是将具有相同ID的行放在一起,然后按照“组”中的最新日期对这些“组”行进行排序 如果我最初的结果是:Sql &引用;“集团”;排序前将某些行合并在一起(Oracle),sql,oracle,plsql,oracle11g,Sql,Oracle,Plsql,Oracle11g,我正在使用Oracle数据库11g。 我有一个从表中选择ID和日期的查询。基本上,我想做的是将具有相同ID的行放在一起,然后按照“组”中的最新日期对这些“组”行进行排序 如果我最初的结果是: ID Date 3 11/26/11 1 1/5/12 2 6/3/13 2 10/15/13 1 7/5/13 我希望的结果是: ID Date 3 11/26/11 <-- (Using this date for "group" ID = 3
ID Date
3 11/26/11
1 1/5/12
2 6/3/13
2 10/15/13
1 7/5/13
我希望的结果是:
ID Date
3 11/26/11 <-- (Using this date for "group" ID = 3)
1 1/5/12
1 7/5/13 <-- (Using this date for "group" ID = 1)
2 6/3/13
2 10/15/13 <-- (Using this date for "group" ID = 2)
ID日期
3 11/26/11一种方法是使用解析函数;我手头没有这样的例子
这是获得指定结果的另一种方法,无需使用分析函数(这是先按每个ID的最新日期排序,然后按ID排序,然后按日期排序):
这里的“诀窍”是为每个ID返回“最近的日期”,然后将其连接到每一行。结果可以先按这个顺序排列,然后再按其他任何顺序排列
(我也认为有一种方法可以使用解析函数获得相同的排序,但我手头没有这样的例子。)一种方法是使用解析函数;我手头没有这样的例子
这是获得指定结果的另一种方法,无需使用分析函数(这是先按每个ID的最新日期排序,然后按ID排序,然后按日期排序):
这里的“诀窍”是为每个ID返回“最近的日期”,然后将其连接到每一行。结果可以先按这个顺序排列,然后再按其他任何顺序排列
(我也认为有一种方法可以使用分析函数获得相同的排序,但我手头没有这样的示例。)您可以使用MAX。。。将
函数与聚合一起使用以创建排序键:
with
sample_data as
(select 3 id, to_date('11/26/11','MM/DD/RR') date_col from dual union all
select 1, to_date('1/5/12','MM/DD/RR') date_col from dual union all
select 2, to_date('6/3/13','MM/DD/RR') date_col from dual union all
select 2, to_date('10/15/13','MM/DD/RR') date_col from dual union all
select 1, to_date('7/5/13','MM/DD/RR') date_col from dual)
select
id,
date_col,
-- For illustration purposes, does not need to be selected:
max(date_col) keep (dense_rank last order by date_col) over (partition by id) sort_key
from sample_data
order by max(date_col) keep (dense_rank last order by date_col) over (partition by id);
您可以使用MAX。。。将
函数与聚合一起使用以创建排序键:
with
sample_data as
(select 3 id, to_date('11/26/11','MM/DD/RR') date_col from dual union all
select 1, to_date('1/5/12','MM/DD/RR') date_col from dual union all
select 2, to_date('6/3/13','MM/DD/RR') date_col from dual union all
select 2, to_date('10/15/13','MM/DD/RR') date_col from dual union all
select 1, to_date('7/5/13','MM/DD/RR') date_col from dual)
select
id,
date_col,
-- For illustration purposes, does not need to be selected:
max(date_col) keep (dense_rank last order by date_col) over (partition by id) sort_key
from sample_data
order by max(date_col) keep (dense_rank last order by date_col) over (partition by id);
以下是使用分析函数的查询:
select
id
, date_
, max(date_) over (partition by id) as max_date
from table_name
order by max_date, id
;
以下是使用分析函数的查询:
select
id
, date_
, max(date_) over (partition by id) as max_date
from table_name
order by max_date, id
;
谢谢你修改了格式,我是新手。谢谢你修改了格式,我是新手