Oracle找到条件最大值

时间:2017-03-20 03:34:25

标签: oracle max

我的结果集如下:

DATE_COL_1     KEY
--------------------------------
2013-12-01     1
2013-12-01     2
2013-12-01     3
2013-12-05     4
2014-01-02     5
2015-12-12     6
2013-11-05     7

是否可以在Oracle DB中使用查询来查找小于或等于当前值但不是相同记录的MAX(DATE_COL_1),以便得到如下结果:

DATE_COL_1     KEY   R
------------------------------------------
2013-12-01     1     2013-12-01
2013-12-01     2     2013-12-01
2013-12-01     3     2013-12-01
2013-12-05     4     2013-12-01
2014-01-02     5     2013-12-05
2015-12-12     6     2014-01-02
2013-11-05     7     (NULL)

感谢所有建议

1 个答案:

答案 0 :(得分:0)

使用子查询进行简单的推理

with s(DATE_COL_1,KEY) as (
select date'2013-12-01',     1 from dual union all 
select date'2013-12-01',     2 from dual union all 
select date'2013-12-01',     3 from dual union all 
select date'2013-12-05',     4 from dual union all 
select date'2014-01-02',     5 from dual union all 
select date'2015-12-12',     6 from dual union all 
select date'2013-11-05',     7 from dual )
select DATE_COL_1
      ,KEY
      ,(select max(DATE_COL_1) from s subs where subs.date_col_1 <= s.date_col_1 and subs.key != s.key)
  from s;