Find and sum difference between timestamps in seconds in PostgreSQL using JOOQ

时光怂恿深爱的人放手 提交于 2019-12-11 03:58:51

问题


This is a follow up question to another question of mine (Find difference between timestamps in seconds in PostgreSQL using JOOQ).

I want to to sum the diff of TIMETRACKS.ENDTIME and TIMETRACKS.STARTTIME in seconds. It can happen that there will not be any TIMETRACKS in the database. In this case the database should return 0 instead.

Thats how the TIMETRACKS table looks like:

CREATE TABLE "TimeTracks" (
    "id" uuid PRIMARY KEY,
    "startTime" timestamp NOT NULL,
    "endTime" timestamp,
);

This is one solution that i tried:

coalesce(sum(timestampDiff(TIMETRACKS.ENDTIME, TIMETRACKS.STARTTIME)), 0)

However coalesce does not work with the interval type: org.postgresql.util.PSQLException: ERROR: COALESCE types interval and integer cannot be matched

Another solution that i found on StackOverflow actually works for me but seems a bit "complicated" because i have to write some raw SQL:

coalesce(sum(extractEpochFrom(timestampDiff(TIMETRACKS.ENDTIME, TIMETRACKS.STARTTIME))), 0)

fun extractEpochFrom(field: Field<DayToSecond>): Field<Integer> =
    DSL.field("extract(epoch from {0})", Integer::class.java, field)

Is there any working solution that does not require me to write raw SQL?


回答1:


The only working solution for now is to resort to plain SQL as found here.

coalesce(sum(extractEpochFrom(timestampDiff(TIMETRACKS.ENDTIME, TIMETRACKS.STARTTIME))), 0)

fun extractEpochFrom(field: Field<DayToSecond>): Field<Integer> =
    DSL.field("extract(epoch from {0})", Integer::class.java, field)



回答2:


There is currently (jOOQ 3.11) experimental support for additional, non standard DatePart types, such as DatePart.EPOCH. It might work already with PostgreSQL, but not with other databases.

This support will be improved in future versions, including jOOQ 3.12, see: https://github.com/jOOQ/jOOQ/issues/7794



来源:https://stackoverflow.com/questions/51961787/find-and-sum-difference-between-timestamps-in-seconds-in-postgresql-using-jooq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!