2015-03-03 57 views
-2

我想要做一個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'); 
+0

添加'基於'sysdate' oracle'標籤和'TO_CHAR()'用法 – 2015-03-03 08:49:08

+0

MAX是一個聚集功能,即只一行返回(只要沒有GROUP BY。)那麼爲什麼DISTINCT? – jarlh 2015-03-03 08:58:01

+0

好的,我刪除了不同的,但我不認爲這是商業案例。 – Lumpi 2015-03-03 09:08:07

回答

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; 
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'; 

這是我的問題的唯一的好辦法。希望這可以幫助人們。

相關問題