2017-09-15 81 views
1

我有一個名爲effective的表,它有id,開始時間,結束時間。如何計算PostgreSQL中表中所有行的日期差異?

我想計算所有行的日期差異。我試着像下面的方法,

select DATE_PART('hour', age(endtime,starttime)) OVER (PARTITION BY id) as increase from effective 

但它顯示了以下錯誤

ERROR: OVER specified, but date_part is not a window function nor an aggregate function

我要像一個結果,

id || starttime     || endtime      || hour 
1 || '2017-09-15 14:50:39.312' || '2017-09-15 16:50:34.349'  || 2 
2 || '2017-09-15 14:50:34.349' || '2017-09-15 15:55:48.894319' || 1 
+1

只是刪除'over'子句。 –

+0

它違反了我使用分區的語法。 – nmkyuppie

+0

我假設@VamsiPrabhala表示整個子句「OVER(PARTITION BY ID)」而不是「OVER」 –

回答

2

使用date_part和減去倍。

SELECT id, starttime, endtime, date_part('hour',endtime-starttime) AS hour 
FROM effective 

輸出

id starttime   endtime    hour 
1 2017-09-15T14:50:39Z 2017-09-15T16:50:34Z 1 
2 2017-09-15T14:50:34Z 2017-09-15T15:55:48Z 1 

SQL小提琴:http://sqlfiddle.com/#!15/916ac9/2/0

另外ID 1開始到結束是隻需1小時59分55秒,而不是2小時。