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?