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.
Code
-- 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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What are the relations in play here?
- The references are `timesheets`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.