我想做一个sql语句,它在一个表中计算2个Date值的减法。如果值为负,我只想将其显示为0值。
数字值是付款处于当前状态的秒数。 我将它用技巧转换为时间值(日期类型)。
我目前的代码是
SELECT
max(CASE WHEN t1.time_event < SYSDATE and t2.time_event > SYSDATE THEN to_char(to_date(max(round(SYSDATE - t1.time_event) * 24 * 60 * 60)),'ssssss'),'hh24:mi:ss') else to_char(to_date(0)) END) as "current_age"
from tbl_dummyfeed t1 join tbl_dummyfeed t2 on t1.payment_Id = t2.payment_id
where t1.event = 'accepted' and t2.event = 'enriched');
答案 0 :(得分:0)
这是有效的,只有转换到时间hh24:mi:ss仍然需要发生。
SELECT max(CASE WHEN t1.time_event < SYSDATE and t2.time_event > SYSDATE THEN round((SYSDATE - t1.time_event) * 24 * 60 * 60) else 0 END) as "current_age"
from tbl_dummyfeed t1 join tbl_dummyfeed t2 on t1.payment_id= t2.payment_id
where t1.event = 'accepted' and t2.event = 'enriched';
当我将转换添加到hh24:mm:ss解决方案看起来像这样
SELECT to_char(to_date(max(CASE WHEN t1.time_event < SYSDATE and t2.time_event > SYSDATE THEN round((SYSDATE - t1.time_event) * 24 * 60
* 60) else 0 END),'sssss'),'hh24:mi:ss') as "current_age" from tbl_dummyfeed t1 join tbl_dummyfeed t2 on t1.trax_Id = t2.trax_id where t1.event = 'accepted' and t2.event = 'enriched';
这是我的问题的唯一好方法。希望这有助于人们。
答案 1 :(得分:0)
您可以使用类似的日期'技巧',即将小数天差异添加到名义日期,其中时间部分为午夜 - 您可以使用固定日期或trunc(sysdate)
,因为时间结束为午夜 - 而不必乘以24 * 60 * 60。 (你的to_date()
解决方案隐含地执行相同的操作,有效地将当前月份的第一天的午夜数添加到午夜;但这可能会更清楚一点。但您也可以将case
子句移到where
过滤器
select to_char(date '1970-01-01'
+ nvl(max(sysdate - t1.time_event), 0), 'HH24:MI:SS') as "current_age"
from tbl_dummyfeed t1
join tbl_dummyfeed t2
on t1.trax_id = t2.trax_id
where t1.event = 'accepted'
and t1.time_event < sysdate
and t2.event = 'enriched'
and t2.time_event > sysdate;
您还可以使用分析方法,因此您只需要打一次表,使用子查询将每个“丰富”时间与该ID的先前“已接受”时间配对,然后根据当前过滤时间:
select to_char(date '1970-01-01'
+ nvl(max(sysdate - time_accepted), 0), 'HH24:MI:SS') as "current_age"
from (
select last_value(case when event = 'accepted' then time_event end ignore nulls)
over (partition by trax_id order by time_event) as time_accepted,
case when event = 'enriched' then time_event end as time_enriched
from tbl_dummyfeed
)
where time_accepted < sysdate
and time_enriched > sysdate;