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.

SqlData Integrity

Code

snippet
-- 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