简体   繁体   中英

SELECT average timestamp difference in JPA with Postgres and HSQL

I have a table with two timestamp columns, startTime and stopTime , and I would like to calculate the average difference of these timestamps in my table. I have a solution that works in Postgres and in HSQLDB (which I use for local unit testing) but not both, and I'm having trouble trying to figure out a common solution.

Postgres:

 select EXTRACT(EPOCH FROM(avg(m.stopTime - m.startTime))) from Measures m 

HSQL:

 select avg(FUNC('UNIX_TIMESTAMP', m.stopTime) - FUNC('UNIX_TIMESTAMP', m.startTime) from Measures m

Is there a way to use the same query for both databases? All of the functions I've found seem to only be supported in one database or the other.

I think my main problem is that there isn't a common function to convert a timestamp to seconds in order to perform the calculation. EPOCH is only compatible with Postgres and UNIX_TIMESTAMP is only compatible with HSQL.

The crux of your problem is converting the dates and timestamps down to a number of seconds. Instead of using epoch, I'll use a julian date for the date. I'll convert the julian date to seconds, then add the number of seconds since minight for each timestamp being compared. The following query does not calculate the difference, it simply converts the date to a number that's similar on both platforms .. you'll have to do this once for each date being compared. note: replace "current"timestamp" with m.startTime and m.stopTime respectively.

select 
(to_number(to_char(current_timestamp,'J'),'99999999999999999999')*86400/*convert from julian days to julian seconds*/) 
       + (to_number(to_char(current_timestamp,'HH'),'99') * 3600) /*Hours to seconds */
       +  (to_number(to_char(current_timestamp,'MM'),'99') * 60) /*Minutes to seconds */
       +  (to_number(to_char(current_timestamp,'SS'),'99') /*add in the seconds*/

Ugly as sin, I know-- perhaps you can rewrite it easier as function, but as I don't know hsqls full feature set, I'll leave it in this form rather than using a CTE or function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM