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

前端 未结 8 2212
轮回少年
轮回少年 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:07

    The following function is returning the number of full weekend days between two dates. As you need full days, you can cast the timestamps to dates before calling the function. It returns 0 in case the first date is not strictly before the second.

    CREATE FUNCTION count_full_weekend_days(date, date)
      RETURNS int AS
    $BODY$
      SELECT
        ($1 < $2)::int
          *
        (
          (($2 - $1) / 7) * 2
            + 
          (EXTRACT(dow FROM $1)<6 AND EXTRACT(dow FROM $2)>0 AND EXTRACT(dow FROM $1)>EXTRACT(dow FROM $2))::int * 2
            +
          (EXTRACT(dow FROM $1)=6 AND EXTRACT(dow FROM $2)>0)::int
            +
          (EXTRACT(dow FROM $2)=0 AND EXTRACT(dow FROM $1)<6)::int
        );
    $BODY$
      LANGUAGE 'SQL' IMMUTABLE STRICT;
    

    Examples:

    SELECT COUNT_FULL_WEEKEND_DAYS('2009-04-10', '2009-04-20');
    # returns 4
    
    SELECT COUNT_FULL_WEEKEND_DAYS('2009-04-11', '2009-04-20');
    # returns 3 (11th is Saturday, so it shouldn't be counted as full day)
    
    SELECT COUNT_FULL_WEEKEND_DAYS('2009-04-12', '2009-04-20');
    # returns 2 (12th is Sunday, so it shouldn't be counted as full day)
    
    SELECT COUNT_FULL_WEEKEND_DAYS('2009-04-13', '2009-04-20');
    # returns 2
    

    To obtain the number of days except full weekend days, simply subtract the number of days from the function above:

    SELECT
      '2009-04-20'::date
        -
      '2009-04-13'::date
        -
       COUNT_FULL_WEEKEND_DAYS('2009-04-13', '2009-04-20');
    

提交回复
热议问题