SQL:结合大小写和数字到日期的转换
问题描述:
我想要做一个sql语句,它在一个表中计算两个日期值的减法。如果该值为负值,我只想将其显示为0值。SQL:结合大小写和数字到日期的转换
数字值是付款处于当前状态的秒数。 我把它与技巧转换为时间值(日期类型)。
我当前的代码是
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');
答
您可以使用类似的日期'技巧',即将小数天差额添加到名义日期(其中时间部分为午夜) - 您可以使用固定日期或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;
答
这工作,只有转化为时间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';
这是我的问题的唯一的好办法。希望这可以帮助人们。
添加'基于'sysdate' oracle'标签和'TO_CHAR()'用法 – 2015-03-03 08:49:08
MAX是一个聚集功能,即只一行返回(只要没有GROUP BY。)那么为什么DISTINCT? – jarlh 2015-03-03 08:58:01
好的,我删除了不同的,但我不认为这是商业案例。 – Lumpi 2015-03-03 09:08:07