Date Trunc Calendar Bucketing
Truncate timestamps to calendar boundaries with date_trunc, then group on the result so counts align to real months, weeks, and hours.
Code
-- date_trunc 按日历边界截断:month 落到月初,week 落到周一,hour 落到整点
SELECT
event_at,
date_trunc('month', event_at) AS month_bucket,
date_trunc('week', event_at) AS week_bucket,
date_trunc('hour', event_at) AS hour_bucket
FROM (VALUES
(TIMESTAMP '2026-11-14 15:42:07'),
(TIMESTAMP '2026-11-30 09:00:00')
) AS events(event_at);
-- 截断结果即可 GROUP BY:计数自动对齐日历口径
SELECT
date_trunc('month', event_at) AS month,
count(*) AS events
FROM (VALUES
(TIMESTAMP '2026-11-14 15:42:07'),
(TIMESTAMP '2026-11-30 09:00:00'),
(TIMESTAMP '2026-12-02 10:00:00')
) AS events(event_at)
GROUP BY date_trunc('month', event_at)
ORDER BY month;Inside the snippet
Several statements share this file — SELECT, with `` among the objects involved.
Breaking the statements into their working parts: COUNT aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.
Key statements
SELECT
date_trunc('month', event_at) AS month,
count(*) AS events
FROM (VALUES
(TIMESTAMP '2026-11-14 15:42:07'),
(TIMESTAMP '2026-11-30 09:00:00'),
(TIMESTAMP '2026-12-02 10:00:00')
) AS events(event_at)
GROUP BY date_trunc('month', event_at)
ORDER BY month;
SELECT
event_at,
date_trunc('month', event_at) AS month_bucket,
date_trunc('week', event_at) AS week_bucket,
date_trunc('hour', event_at) AS hour_bucket
FROM (VALUES
(TIMESTAMP '2026-11-14 15:42:07'),
(TIMESTAMP '2026-11-30 09:00:00')
) AS events(event_at);
Interactive Tools for This Topic
Age CalculatorCalculate exact age in years, months, and days between a birth date and a reference date, plus total days and the next birthday countdown.Business Days CalculatorCount the weekdays between two dates, excluding weekends and any holidays you list, and see how many calendar and weekend days are involved.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.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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.