2015-02-15 23 views
11

Ho una tabella di elementi con le seguenti colonne:Aggiunta <integer> secondi per un <timestamp> in PostgreSQL

  • start_time colonna (timestamp without time zone)
  • expiration_time_seconds colonna (integer)

Ad esempio, alcuni valori sono:

SELECT start_time, expiration_time_seconds 
    FROM whatever 
     ORDER BY start_time; 

     start_time   | expiration_time_seconds 
----------------------------+------------------------- 
2014-08-05 08:23:32.428452 |     172800 
2014-08-10 09:49:51.082456 |     3600 
2014-08-13 13:03:56.980073 |     3600 
2014-08-21 06:31:38.596451 |     3600 
... 

Come si aggiunge la data di scadenza, espressa in secondi, a start_time?

ho cercato di formattare una stringa intervallo di tempo per il comando interval, ma fallito:

blah=> SELECT interval concat(to_char(3600, '9999'), ' seconds'); 
ERROR: syntax error at or near "(" 
LINE 1: SELECT interval concat(to_char(3600, '9999'), ' seconds'); 

risposta

22

Il trick è creare un intervallo fisso e moltiplicarlo con il numero di secondi nella colonna:

SELECT start_time, 
     expiration_time_seconds, 
     start_time+expiration_time_seconds * interval '1 second' 
    FROM whatever 
     ORDER BY start_time; 

     start_time   | expiration_time_seconds |   end_time 
----------------------------+-------------------------+---------------------------- 
2014-08-05 08:23:32.428452 |     172800 | 2014-08-07 08:23:32.428452 
2014-08-10 09:49:51.082456 |     3600 | 2014-08-10 10:49:51.082456 
2014-08-13 13:03:56.980073 |     3600 | 2014-08-13 14:03:56.980073 
2014-08-21 06:31:38.596451 |     3600 | 2014-08-21 07:31:38.596451 
+1

impressionante. grazie... – des1roer