Getting number of certain days-of-the-week (weekend) from interval in PostgreSQL

前端 未结 8 2074
轮回少年
轮回少年 2021-01-06 13:27

Given 2 timestamps in postgres, how do you calculate the time difference without counting whole Saturdays and Sundays?

OR

How do you count the number of Satu

8条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-06 14:04

    This should answer the second part of your question:

    create or replace function is_weekend_day(date) returns boolean
     strict immutable language 'sql'
     as $$ select case extract(dow from $1) when 0 then true when 6 then true else false end $$;
    
    create or replace function count_weekend_days(start_date date, end_date date) returns int
     strict immutable language 'sql'
     as $$
    select cast(sum(case when is_weekend_day($1 + ofs) then 1 else 0 end) as int)
    from generate_series(0, $2 - $1) ofs
    $$;
    

    Making a corresponding count_non_weekend_days is simple after that.

提交回复
热议问题