justify_interval Normalize Overspill
justify_interval folds raw interval components into days, hours, and minutes so a computed duration prints as a stable single unit set.
Code
-- 原始区间按"你给的字段"存储:30 hours 就是 30 hours,不会自动进位
SELECT interval '30 hours 90 minutes' AS raw,
justify_hours(interval '30 hours 90 minutes') AS hours_folded,
justify_interval(interval '30 hours 90 minutes') AS fully_folded;
-- 天/时/分混算后字段溢出:归一让报表口径统一
SELECT justify_days(interval '45 days') AS days_folded,
justify_interval(interval '1 month 45 days 25 hours') AS normalized;
-- 会话时长统计:SUM 之后直接归一,避免"49.5 hours"这类难读输出
CREATE TABLE work_sessions (
worker text,
started_at timestamptz,
ended_at timestamptz
);
INSERT INTO work_sessions VALUES
('ada', timestamptz '2026-11-14 09:00+00', timestamptz '2026-11-14 17:30+00'),
('ada', timestamptz '2026-11-15 09:00+00', timestamptz '2026-11-15 15:00+00');
SELECT worker,
SUM(ended_at - started_at) AS raw_total,
justify_interval(SUM(ended_at - started_at)) AS readable_total
FROM work_sessions
GROUP BY worker;
DROP TABLE work_sessions;What the code does
Several statements share this file — SELECT / INSERT / CREATE, with work_sessions among the objects involved.
Mechanically, the statements are built from: SUM aggregation; a GROUP BY that collapses matching rows into one output row per group.
Using it
Run it in the work_sessions database context.
Key statements
SELECT worker,
SUM(ended_at - started_at) AS raw_total,
justify_interval(SUM(ended_at - started_at)) AS readable_total
FROM work_sessions
GROUP BY worker;
INSERT INTO work_sessions VALUES
('ada', timestamptz '2026-11-14 09:00+00', timestamptz '2026-11-14 17:30+00'),
('ada', timestamptz '2026-11-15 09:00+00', timestamptz '2026-11-15 15:00+00');
SELECT interval '30 hours 90 minutes' AS raw,
justify_hours(interval '30 hours 90 minutes') AS hours_folded,
justify_interval(interval '30 hours 90 minutes') AS fully_folded;
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.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.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.
FAQ
- What objects does the SQL involve?
- `work_sessions`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.