您好我想在两个日期之间显示SQL差异:
* END DATE = dt_termino / now()
* START DATE = dt_inicio
我有一个用CSV写的函数...但在我的csv输出中如下:
id_task_tarefa | dt_inicio | dt_termino | sum
211 | 2016-01-25 10:40:25 | 2016-01-27 08:51:02 | 01 22:10:37
210 | 2016-01-25 10:40:29 | 2016-01-27 08:50:21 | 01 22:09:52
我需要一个格式输出Excel [h]:mm:ss; @ 像这样
id_task_tarefa | dt_inicio | dt_termino | sum
211 | 2016-01-25 10:40:25 | 2016-01-27 08:51:02 | 46:10:37
210 | 2016-01-25 10:40:29 | 2016-01-27 08:50:21 | 46:09:52
这是我的SQL:
SELECT id_task_tarefa,
dt_inicio,
dt_termino,
to_char(COALESCE(dt_termino::timestamp, now()::timestamp)
- dt_inicio::timestamp,'DD HH24:MI:SS')
FROM crm.task_interacao
答案 0 :(得分:3)
不确定是否有更好的方法,但有效
SELECT '2016-01-25 10:40:25' start_date,
'2016-01-27 08:51:02' end_date,
to_char('2016-01-27 08:51:02'::timestamp
- '2016-01-25 10:40:25'::timestamp,'HH24:MI:SS') as sum_text,
TRUNC(EXTRACT(epoch FROM '2016-01-27 08:51:02'::timestamp - '2016-01-25 10:40:25'::timestamp)/3600) time_diff,
TRUNC(EXTRACT(epoch FROM '2016-01-27 08:51:02'::timestamp - '2016-01-25 10:40:25'::timestamp)/3600) || ':' ||
to_char('2016-01-27 08:51:02'::timestamp
- '2016-01-25 10:40:25'::timestamp,'MI:SS') result
<强>输出强>
答案 1 :(得分:2)
这个功能对您来说很方便:
create or replace function interval_in_hours(interval)
returns text language sql as $$
select format('%s:%s',
(extract (epoch from $1) / 3600)::int,
to_char($1, 'mi:ss'))
$$;
使用:
with the_data (id_task_tarefa, dt_inicio, dt_termino) as (
values
(211, timestamp '2016-01-25 10:40:25', timestamp '2016-01-27 08:51:02'),
(210, timestamp '2016-01-25 10:40:29', timestamp '2016-01-27 08:50:21')
)
select *, interval_in_hours(dt_termino- dt_inicio)::interval as sum
from the_data;
id_task_tarefa | dt_inicio | dt_termino | sum
----------------+---------------------+---------------------+----------
211 | 2016-01-25 10:40:25 | 2016-01-27 08:51:02 | 46:10:37
210 | 2016-01-25 10:40:29 | 2016-01-27 08:50:21 | 46:09:52
(2 rows)