-1

Sample table:

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

Hi, can someone pl. help how do I get the least date and corresponding name from the table above? I should get only 3 rows, with first one as Ram and second one as def and third one as def.

Thanks

MT0
  • 143,790
  • 11
  • 59
  • 117
Prakash
  • 17
  • 1
  • 7

2 Answers2

2

This is a special case of a top N per category style query, which can be implemented efficiently in 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

Other solutions include:

Window functions

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

Subqueries

As suggested by Yogesh, but they're way slower than the above solutions.

GolezTrol
  • 114,394
  • 18
  • 182
  • 210
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
2

Use subquery or ranking function :

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

You can also use row_number ranking function

select * 
from (select *,
             row_number() over (partition by Id order by StartTime) Seq
      from table t
     ) t
where Seq = 1;
Yogesh Sharma
  • 49,870
  • 5
  • 26
  • 52