2014-05-12 97 views
2

我期待以天/小時/分鐘爲單位計算兩個日期之間的差異。Oracle中同一列中兩個日期之間的差異以天/小時/分鐘爲單位

我有一個表數據結構如下:

ID     Date       Location   Type 
--------------------------------------------------------------------------------- 
42ABC   15-NOV-14 12.45.00 PM     YY   Departed 
42ABC   15-NOV-14 03.10.00 PM     AA   Arrived 
42ABC   18-NOV-14 05.15.00 PM     AA   Departed 
42ABC   18-NOV-14 07.20.00 PM     YY   Arrived 

如何計算的差異日期,並獲得這樣的:

ID    Location     DURATION 
----------------------------------------------------------------- 
42ABC    AA     3 days, 2 hours, 5 minutes 

我很欣賞你在此輸入。

回答

1

,想到的第一個解決方案是:

SELECT id, 
     location, 
      TRUNC (date_diff) 
     || ' days, ' 
     || TRUNC ((date_diff - TRUNC (date_diff)) * 24) 
     || ' hours, ' 
     || MOD ((date_diff - TRUNC (date_diff)) * 24, 10) * 60 
     || ' minutes' 
FROM (SELECT id, location, MAX (date) - MIN (date) AS date_diff 
     FROM  your_table 
     GROUP BY id, location) 

當你減去在Oracle中兩個日期,結果是一個表示天數的十進制數,所以它從那裏只是數學拿出小時和分鐘。如果你想讓它變得更加複雜(例如,如果數字爲零,則刪除部分),那麼我建議使用一個函數。

它也可以是能夠通過從date轉換爲使用稍微簡單的解決方案,以timestamp,其產生interval類型的結果,而不是一個decimal


interval溶液:

SELECT id, 
     location, 
      EXTRACT (DAY FROM date_diff) 
     || ' days, ' 
     || EXTRACT (HOUR FROM date_diff) 
     || ' hours, ' 
     || EXTRACT (MINUTE FROM date_diff) 
     || ' minutes' 
FROM (SELECT id, location, 
       CAST(MAX (date) as timestamp) 
       - CAST(MIN (date) as timestamp) AS date_diff 
     FROM  your_table 
     GROUP BY id, location) 
0

這可以是確定:

select T1.ID, T2.LOCATION, round(T2.DDATE - T1.DDATE) || ' days, ' || 
      trunc(mod((T2.DDATE - T1.DDATE)*24, 24)) || ' hours, ' || 
      trunc(mod((T2.DDATE - T1.DDATE)*24*60, 60)) || ' minutes' duration 
from YOUR_TABLE T1, YOUR_TABLE T2 
where T2.ID = T1.ID 
    and T2.LOCATION = T1.LOCATION 
    and T1.TYPE = 'Arrived' 
    and T2.TYPE = 'Departed' 
; 
相關問題