2017-01-08 86 views
0

我需要將以下(hh)整數列轉換爲時間列。預期結果如下:Postgres將整數轉換爲時間

hh  time 
1  00:00 
2  00:30 
3  01:00 
4  01:30 
... 
48  23:30 

你能幫忙嗎?

+0

這是第4半小時出48半小時。 – user636322

+0

'select(make_interval(mins:=(hh-1)* 30)):: time;' – Abelisto

回答

2

你可以這樣做:

select hh, ('00:00:00'::time + (hh - 1) * interval '30 minute') as time 
from t; 
+0

偉大的作品就像一個魅力。謝謝 – user636322

1

Use INTERVAL arithmetic

SELECT 
    TIME '00:00' + (1 - 1) * INTERVAL '30 minutes', 
    TIME '00:00' + (2 - 1) * INTERVAL '30 minutes', 
    TIME '00:00' + (3 - 1) * INTERVAL '30 minutes', 
    TIME '00:00' + (4 - 1) * INTERVAL '30 minutes', 
    TIME '00:00' + (5 - 1) * INTERVAL '30 minutes', 
    -- ... 
    TIME '00:00' + (48 - 1) * INTERVAL '30 minutes' 

另一個解決方案是使用UNIX時間戳的工作:

SELECT 
    (to_timestamp((1 - 1) * 30 * 60) at time zone 'UTC')::time, 
    (to_timestamp((2 - 1) * 30 * 60) at time zone 'UTC')::time, 
    (to_timestamp((3 - 1) * 30 * 60) at time zone 'UTC')::time, 
    (to_timestamp((4 - 1) * 30 * 60) at time zone 'UTC')::time, 
    (to_timestamp((5 - 1) * 30 * 60) at time zone 'UTC')::time, 
    -- ... 
    (to_timestamp((48 - 1) * 30 * 60) at time zone 'UTC')::time