Question

Possible Duplicate:
How to display the record with the highest value in Oracle?

I am supposed to display the name and age of the oldest person from the database. The code I used displays the name and the calculated age of several people, but it won't display the single oldest person. How do I get this to work? here is my code

select dr_drvname as "Name", trunc(max((sysdate-dr_brthdate)/365)) as "Highest AGE"
from driver,dual
group by dr_drvname;
Was it helpful?

Solution

Another way in Oracle would be something like:

SELECT
    dr_drvname AS "Name",
    trunc(months_between(sysdate, dr_birthdate) / 12) AS "Highest Age"
FROM
(
SELECT
    dr_drvname,
    dr_birthdate
FROM
    driver
ORDER BY
    dr_birthdate
)
WHERE
    ROWNUM = 1;

OTHER TIPS

Try something like this:

SELECT top 1
  Firstname, LastName, Max([BirthDate]) as Oldest    
  FROM [Employees]
  group by BirthDate, FirstName, LastName

Note: What are the requirements if multiple people have the same birth date?

You can use analytic functions

select dr_drvname as "Name", 
       trunc( months_between( sysdate, dr_birthdate )/ 12 ) "Highest Age"
  from (select dr_drvname ,
               dr_birthdate,
               rank() over (order by dr_birthdate) rnk
          from driver)
 where rnk = 1;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top