找到适合2个日期操作的匹配

时间:2011-05-13 18:36:47

标签: sql oracle oracle10g

我想查找Patients.dobPatient.dob - 20之间的所有patient.dob -30(以年为单位)。

我正在使用Oracle 10g,并尝试dateAdd并尝试替换SYSTIME - 12*30,但都不起作用。

数据已正确加载,并且应采用日期格式。

如何做到这一点?

2 个答案:

答案 0 :(得分:0)

您可以使用add_months来执行此操作:

select * from patient p 
  where 
    add_months(p.dob,30 * 12) > current_date and 
    add_months(p.dob,20 * 12) < current_date;

答案 1 :(得分:0)

你可以提取年份并在两者之间进行(但这种方式只能获得年份差异,没有必要确切的20 - 30年差异)

with datam as
(
 select level id, sysdate - level dob
   from dual 
 connect by level < 15000)

 select count(id) count_id , extract(year from dob)
   from datam
  where extract(year from dob) between 2011-30 and 2011-20
  group by extract(year from dob)
  order by 2 desc 

但是,忽略闰年(这是你试图用12 * 30做的,应该是365 * 12)

with datam as
(
 select level id, sysdate - level dob
   from dual 
 connect by level < 15000)

 select count(id) count_id , extract(year from dob)
   from datam
  where dob between (sysdate - 365*30) and (sysdate - 365*20)
  group by extract(year from dob)
  order by 2 desc ;

但是@ Briguy37也有效:

with datam as
(
 select level id, sysdate - level dob
   from dual 
 connect by level < 15000)

 select count(id) count_id , extract(year from dob)
   from datam
  where dob between add_months(dob,- 12*30) and add_months(sysdate,- 12*20)
  group by extract(year from dob)
  order by 2 desc ;