Business Days With Generate Series

Count business days between two dates with generate_series over the day range and an ISODOW filter, keeping Monday-Friday and dropping weekends.

SqlCli Tooling

Code

snippet
-- 两个日期之间的工作日天数:ISODOW 周一=1、周日=7
WITH span AS (
    SELECT date '2026-01-01' AS start_day,
           date '2026-01-31' AS end_day
),
days AS (
    SELECT generate_series(start_day, end_day, interval '1 day')::date AS day
    FROM span
)
SELECT COUNT(*) FILTER (WHERE EXTRACT(ISODOW FROM day) < 6) AS business_days,
       COUNT(*) AS calendar_days
FROM days;

How it works

What runs is SELECT, with span, day and days as the object involved.

Breaking the statements into their working parts: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause limiting a statement to the rows that qualify; COUNT aggregation.

Putting it to use

Run the statement against the span table.

Interactive Tools for This Topic

FAQ

Which relations are involved here?
`span`, `day`, `days` — referenced directly, no join needed.