我需要找到格式为hh:mm:ss的时间之间的差异
select msglog.id,max(msglog.timestamp) enddate,min(msglog.timestamp) startdate,enddate - startdate from MESSAGELOG msglog group by id
在上面的查询中,msglog.timestamp的类型为DATE.
如何在oracle中以正确的格式获取经过的时间或差异?
当您减去两个DATE值(如enddate – startdate)时,您会得到带小数精度的天数差异,因此例如1.5表示1 1/2天或36小时.您可以使用大量数学将其转换为HH:MI:SS,但更简单的方法是使用
NUMTODSINTERVAL
函数将十进制值转换为INTERVAL DAY TO SECOND值:
NUMTODSINTERVAL(enddate - startdate,'DAY')
您认为TO_CHAR函数可以将其格式化为HH:MI:SS,但它似乎不会那样工作.您可以使用EXTRACT和TO_CHAR来确保获得前导零:
TO_CHAR(EXTRACT(HOUR FROM NUMTODSINTERVAL(enddate-startdate,'DAY')),'FM00') || ':' || TO_CHAR(EXTRACT(MINUTE FROM NUMTODSINTERVAL(enddate-startdate,'FM00') || ':' || TO_CHAR(EXTRACT(SECOND FROM NUMTODSINTERVAL(enddate-startdate,'FM00')
格式代码的00部分指定两个数字,如果需要,前导零. FM部分摆脱了格式化结果中的前导空格,可以为负号保留.
另请注意,您的查询获取聚合值并在同一SELECT列表中使用它们. Oracle不会让你这样做.尝试这样的事情:
WITH StartEndByID AS ( SELECT msglog.id,NUMTODSINTERVAL(max(msglog.timestamp) - min(msglog.timestamp),'DAY') elapsed FROM messagelog msglog GROUP BY id ) SELECT id,TO_CHAR(EXTRACT(HOUR FROM elapsed),'FM00') || ':' || TO_CHAR(EXTRACT(MINUTE FROM elapsed),'FM00') || ':' || TO_CHAR(EXTRACT(SECOND FROM elapsed),'FM00') AS ElapsedHHMISS FROM StartEndByID