我希望以天/小时/分钟来计算两个日期之间的差异。
我有一个包含以下数据结构的表:
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
感谢您对此的投入。
答案 0 :(得分: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)
答案 1 :(得分: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'
;