Zurück zum Blog

Calculate Time Spans by Quarters of an Hour With SQL

An SQL expression can calculate the duration between two timestamp columns and round it to quarter-hour increments. The result is returned as a positive number of hours. A simple example demonstrates the expected output for a typical time span.

#SQL#Java
Datenbank-Symbolbild für SQL
#SQL

Suppose you have a database table containing two fields ‘start’ and ‘end’ of type timestamp denoting the starting time and ending time, respectively, of some time span. You can calculate the positive time span between these two points in time rounded to the nearest quarter of an hour with the following SQL snippet:

SELECT
 ABS(EXTRACT (HOUR FROM table.end - table.start) +
 (ROUND((EXTRACT (MINUTE FROM table.end - table.start))
 / 15) * 0.25))
FROM
 schema.table

For example, this yields for the time span 10:30 – 12:00 a duration of 1.5 hours.