SUM Interval Totals Timesheet Durations

sum(interval) totals durations across rows and stays correct past 24 hours; justify_interval re-splits the pile into days plus hh:mm.

SqlData Integrity

Code

snippet
-- sum(interval) totals the duration column across rows,跨行聚合时长
-- weekly durations add up even past 24h,不会溢出或丢失
WITH timesheets(employee, duration) AS (
    VALUES
        ('ada', interval '12 hours'),
        ('ada', interval '14 hours 30 minutes'),
        ('linus', interval '9 hours 45 minutes'),
        ('linus', interval '6 hours 50 minutes')
)
SELECT
    employee,
    sum(duration) AS total_duration,
    -- justify_interval 把超过一天的累计拆成 days + hh:mm 显示
    justify_interval(sum(duration)) AS normalized
FROM timesheets
GROUP BY employee
ORDER BY employee;

How it works

At its core this is a single SELECT statement against timesheets.

Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; SUM aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.

Putting it to use

Run the statement against the timesheets table.

Interactive Tools for This Topic

FAQ

What are the relations in play here?
The references are `timesheets`.