2016-07-05 114 views
0

我在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) 
+0

你可以只减去两个日期,但在甲骨文的日期基本arithmatic给出的答案在天。 – OTTA

回答

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 
+1

'date_a - date_b'给出两个日期之间的天数差异 - 所以这是检查**日期与非年份之间是否有** 25天**的差异。 – MT0

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. 
); 
+0

add_months在oracle中工作吗? –

+0

是的。 https://docs.oracle.com/cd/B28359_01/server.111/b28286/functions004.htm –

相关问题