计算2个日期的年份

时间:2016-07-05 08:06:33

标签: sql oracle

我在oracle数据库上运行。我想找到所有那些在年满25岁之前接受治疗的人。我知道至少有500,但我得到的结果是0.显然我的查询是错误的。所以我认为问题在于我减去日期的方式。它们都是表中的日期类型。从我看来,应该可以减去两个日期? 有人写道他们使用DATEDIFF,但这对我不起作用。

   select count(*) FROM V_Persons
    where exists(select * from res_tx res, recipient rec, Treatment tr
                where (tr.TREAT_DATE - rec.DATE_OF_BIRTH) < 25 
                and rec.ident = res.ident
                and rec.ident = tr.ident)

2 个答案:

答案 0 :(得分:3)

SELECT COUNT(*)
FROM   V_Persons p
WHERE  EXISTS(
  SELECT 'X'
  FROM   recipient c
         INNER JOIN Treatment r
         ON ( c.ident = r.ident )
         INNER JOIN res_tx s       -- Do you need to join this table?
         ON ( c.ident = s.ident )
  WHERE  r.TREAT_DATE < ADD_MONTHS( c.DATE_OF_BIRTH, 25 * 12 )
  AND    p.ident = c.ident         -- You need to correlate with the outer query.
);

答案 1 :(得分:0)

尝试此操作以解决日期差异是否与您希望在存在子查询内的查询中工作的问题。

select * , (tr.TREAT_DATE - rec.DATE_OF_BIRTH ) as DateDifference
 from res_tx res, recipient rec, Treatment tr
                where (tr.TREAT_DATE - rec.DATE_OF_BIRTH) < 25 
                and rec.ident = res.ident
                and rec.ident = tr.ident