如何针对Oracle中最早的日期字段获取值

时间:2018-08-27 17:06:36

标签: sql oracle oracle11g

我有一个选择查询,该查询从多个表中获取值,其中日期作为字段之一:

select e.id,e.date,d.d_id
from emp e, d_source d
 where e.d_id = d.d_id and e.emp_id = 100` 

对于每个emp_id,都有2条或更多记录。我必须根据最旧的日期值从id表中选择emp。在某些情况下,所有选定记录的日期字段值都为空或日期字段值相同。在这种情况下,我必须选择与d_id表的特定d_source(例如123)关联的ID。

到目前为止我尝试过的是

`select e.id from emp e 
where e.emp_id = 100 
and e.date=(select min(date) from emp where emp_id = 100)`

这些是针对3个不同emp_id-的首次选择查询的一些结果

Select results

因此,我只需要返回具有最旧日期值的记录的“ id”,并且如果日期字段值等于或为空,则需要返回具有d_id为456的记录的“ id”

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

根据我的理解,这是一个例子。

SQL> -- sample data
SQL> with emp (emp_id, id, cdate, d_id) as
  2    (select 100, 11111, date '2010-02-26', 123 from dual union all
  3     select 100, 22222, date '2018-02-26', 456 from dual union all
  4     --
  5     select 200, 11122, date '2010-02-26', 123 from dual union all
  6     select 200, 22211, date '2010-02-26', 456 from dual union all
  7     --
  8     select 300, 11133, null, 123 from dual union all
  9     select 300, 22244, null, 456 from dual
 10    ),
 11  source (d_id) as
 12    (select 123 from dual union all
 13     select 456 from dual
 14    )
 15  -- query that, hopefully, returns result you need
 16  select emp_id, id, cdate, d_id
 17  from (select e.emp_id, e.id, e.cdate, d.d_id,
 18          row_number() over (partition by e.emp_id order by e.cdate, d.d_id desc) rn
 19        from emp e join source d on e.d_id = d.d_id
 20       )
 21  where rn = 1
 22  order by emp_id;

    EMP_ID         ID CDATE            D_ID
---------- ---------- ---------- ----------
       100      11111 26/02/2010        123
       200      22211 26/02/2010        456
       300      22244                   456

SQL>