2017-09-15 52 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小时。