Postgresql время как продолжительность - PullRequest
0 голосов
/ 16 марта 2020

Мне нужно время как длительность в postgresql

Например: - Текущее время 3/16/2020 13:23:0000

запись в столбце таблицы по 3/15/2020 12:23:0000

, поэтому значение мне нужно get это '1 день 1 час a go'

, если это так, 3/16/2020 13: 20: 0000, это должно быть 3 минуты, go, как этот

1 Ответ

2 голосов
/ 16 марта 2020

Вы можете выполнить форматирование в SQL с помощью чего-то вроде:

select * from tt;
          x          
---------------------
 2020-02-16 13:30:41
(1 row)

select current_timestamp;
       current_timestamp       
-------------------------------
 2020-03-16 09:38:24.267299+01
(1 row)

select 
 case when dd > 0 then dd || ' days ' else ' ' end 
 ||
 case when hh > 0 then hh || ' hours ' else ' ' end
 ||
 case when mi > 0 then mi || ' minutes ' else ' ' end 
 || 
 'ago' as when
from
(
 select 
  extract(day from (current_timestamp - x)) as dd,
  extract(hour from (current_timestamp - x)) as hh,
  extract(minute from (current_timestamp - x)) as mi 
  from tt
) as t;
              when              
--------------------------------
 28 days 20 hours 7 minutes ago
(1 row)

Для этого вы можете создать сохраненную функцию:

create or replace function format_timestamp(timestamp) returns text
as
$$
select 
 case when dd > 0 then dd || ' days ' else ' ' end 
 ||
 case when hh > 0 then hh || ' hours ' else ' ' end
 ||
 case when mi > 0 then mi || ' minutes ' else ' ' end 
 || 
 'ago' as when
from
(
 select 
  extract(day from (current_timestamp - $1)) as dd,
  extract(hour from (current_timestamp - $1)) as hh,
  extract(minute from (current_timestamp -$1 )) as mi 
) as t;
$$
language sql;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...