ID || birthdate
------------------------
1 || 25-10-1994
2 || 1-6-1990
3 || 4-12-2006
如何计算年龄以及如何获得第n个最高年龄。
答案 0 :(得分:1)
将months_between
与row_number
一样使用
select m.age from
(select s.age,
ROW_NUMBER() OVER (PARTITION BY s.age ORDER BY s.age desc) rownumber
from (select MONTHS_BETWEEN(sysdate, birthdate )/12 age from myTable) s) m
where m.rownumber = 1 -- or your nth highest age row, for example 11 ))
答案 1 :(得分:0)
我不知道SQL查询的Oracle语法,但您可以按如下方式创建查询:
N
,即第N个最大。答案 2 :(得分:0)
可以通过从sysdate
中减去birtdate来计算年龄。这将以天为单位返回年龄。完成后,这是一个典型的greatest-n-per-group查询。你可以用例如一个窗口函数来过滤掉最老的n:
select id, birthdate, "Age in days"
from (
select id,
birthdate,
sysdate - birthdate as "Age in days",
row_number() over (order by sysdate - birthdate desc) as rn
from emps
)
where rn <= 2 -- or whatever limit you want
order by 3;