oracle sql中的最小日期

时间:2018-05-15 12:16:26

标签: sql oracle greatest-n-per-group

样本表:

https://i.stack.imgur.com/0O8Gh.gif

嗨,有人可以。帮助我如何从上表中获得最少的日期和相应的名称?我应该只获得3行,第一行为Ram,第二行为def,第三行为def。

由于

2 个答案:

答案 0 :(得分:2)

这是a special case of a top N per category style query,可以在Oracle中高效实施。

Using Oracle's FIRST function

SELECT 
  id, 
  MIN(name)      KEEP (DENSE_RANK FIRST ORDER BY starttime) name,
  MIN(starttime) KEEP (DENSE_RANK FIRST ORDER BY starttime) starttime
FROM t
GROUP BY id

其他解决方案包括:

窗口功能

SELECT id, name, starttime
FROM (
  SELECT 
    id, name, starttime, 
    ROW_NUMBER () OVER (PARTITION BY id ORDER BY starttime) rn
  FROM t
) t
WHERE rn = 1

子查询

As suggested by Yogesh,但它们比上述解决方案慢。

答案 1 :(得分:2)

使用subquery排名功能:

select * 
from table t
where StartTime = (select min(StartTime) from table where Id = t.Id);

您还可以使用row_number排名功能

select * 
from (select *,
             row_number() over (partition by Id order by StartTime) Seq
      from table t
     ) t
where Seq = 1;