DB2SQL中TIMESTAMPDIFF的空结果



我正在根据时间戳计算TIMESTAMPDIFF,这些时间戳之间的时间间隔范围相当大,从零点几秒到60多分钟不等。由于DB2中的DB2TIMESTAMPDIFF((函数返回一个整数作为结果,所以我使用微秒作为数值间隔表达式。TIMESTAMPDIFF DB2文档状态:

微秒(持续时间的绝对值必须小于3547.483648(

这相当于大约59分钟,所以超过这个时间的任何间隔都会返回为零值,这就是我试图解决的问题。

我在数据中使用的示例查询/时间戳:

select timestampdiff(1, char(timestamp('2022-09-12 14:30:40.444896') - timestamp('2022-09-12 14:30:40.115789'))) from sysibm.SYSDUMMY1
select timestampdiff(1, char(timestamp('2022-09-12 15:59:14.548636') - timestamp('2022-09-12 14:56:10.791140'))) from sysibm.SYSDUMMY1

上面的第二个查询是一个示例,它在结果超过最大结果间隔限制时返回null值。我习惯于使用微秒作为间隔,因为不到1秒的结果仍然有效。

有没有任何方法可以绕过这个限制来返回超过限制的结果?

SELECT
A, B
, (
(DAYS (A) - DAYS (B)) * DEC (86400, 31)
+ MIDNIGHT_SECONDS (A) - MIDNIGHT_SECONDS (B)
) * 1000
+ (MICROSECOND (A) - MICROSECOND (B)) / 1000
AS DIFF_MS
FROM 
(
VALUES
(timestamp('2022-09-12 14:30:40.444896'), timestamp('2022-09-12 14:30:40.115789'))
, (timestamp('2022-09-12 15:59:14.548636'), timestamp('2022-09-12 14:56:10.791140'))
) T (A, B)
DIFF_MS2022-09-12 14:30:40.4448962022-09-12 14:30:40.1157893292022-09-12 15:59:14.5486362022-09-12 14:56:10.7911403783758

当你减去日期或时间戳时,你会得到一个持续时间。。

持续时间是一个格式化为yyyymmddhhmmss.zzzzzzzzzzzz的数字
来自手册:

A timestamp duration represents a number of years, months, days, hours, minutes, seconds, and
fractional seconds, expressed as a DECIMAL(14+s,s) number, where s is the number of digits of
fractional seconds ranging from 0 to 12. To be properly interpreted, the number must have the format
yyyymmddhhmmss.zzzzzzzzzzzz, where yyyy, mm, dd, hh, mm, ss, and zzzzzzzzzzzz represent,
respectively, the number of years, months, days, hours, minutes, seconds, and fractional seconds. The
result of subtracting one timestamp value from another is a timestamp duration with scale that
matches the maximum timestamp precision of the timestamp operands.
10303.757496

读取为1小时3分3.757496秒

所以如果你愿意,你可以自己计算。最好构建自己的UDF,返回一个大整数,甚至更大的十进制值。

最新更新