MySQL有一个很酷的功能sec_to_time()
它将您的秒数转换为 hh:mm:ss
我已经通读了邮件列表,基本上是在尝试实现以下内容:
MySQL:
select sec_to_time(sum(unix_timestamp(enddate) - unix_timestamp(startdate))) from foo;
PostgreSQL:
select XXX(sum(date_part('epoch',enddate) - date_part('epoch',startdate))) from foo;
我只需要知道 XXX 是什么/可以是什么。我已经尝试了很多已记录功能的组合。
请问如何在 PostgreSQL 中执行此操作?
最佳答案
使用to_char
:
regress=# SELECT to_char( (9999999 ||' seconds')::interval, 'HH24:MM:SS' );
to_char
------------
2777:00:39
(1 row)
这是一个生成文本
格式值的函数:
CREATE OR REPLACE FUNCTION sec_to_time(bigint) RETURNS text AS $$
SELECT to_char( ($1|| ' seconds')::interval, 'HH24:MI:SS');
$$ LANGUAGE 'SQL' IMMUTABLE;
例如:
regress=# SELECT sec_to_time(9999999);
sec_to_time
-------------
2777:00:39
(1 row)
如果您更喜欢 INTERVAL
结果,请使用:
CREATE OR REPLACE FUNCTION sec_to_time(bigint) RETURNS interval AS $$
SELECT justify_interval( ($1|| ' seconds')::interval);
$$ LANGUAGE 'SQL' IMMUTABLE;
... 这将产生如下结果:
SELECT sec_to_time(9999999);
sec_to_time
-------------------------
3 mons 25 days 17:46:39
(1 row)
不要将 INTERVAL
转换为 TIME
;它会丢弃天部分。使用 to_char(theinterval, 'HH24:MI:SS)
将其转换为 text
而不是截断。
关于mysql - PostgreSQL 中的 sec_to_time() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12085307/