定义营业月份:一个月的第一个星期日,直到下个月的第一个星期六

时间:2014-07-08 15:37:40

标签: sql postgresql date datetime calendar

我有一个带有时间戳字段的表。在 Postgresql 中,我必须在当月的第一个星期日到下个月的第一个星期六之间定义一个“营业月”(例如2014-04-06至2014-05-03将是'2014年4月')。

我不太清楚从哪里开始。到目前为止,我从this forum post获得第一个星期日(使用T-SQL)。

--first sunday of this month....
-1=sunday,-2=saturday,-3-friday etc
SELECT
datename(dw,dateadd(dd,-1,DATEADD(wk, 
DATEDIFF(wk,0,dateadd(dd,7-datepart(day,getdate()),getdate())), 0))),
dateadd(dd,-1,DATEADD(wk, 
DATEDIFF(wk,0,dateadd(dd,7-datepart(day,getdate()),getdate())), 0))

我可能需要构建一个日历表并手动定义月份。但我想探索其他解决方案。

1 个答案:

答案 0 :(得分:0)

SQL Fiddle

功能

create or replace function business_month("month" date)
returns table (first_day date, last_day date) as $$

    with first_month_day as (
        select date_trunc('month', month)::date as first_day
    ), first_business_day as (
        select
            first_day
            + (extract(dow from first_day)::int > 0)::int * 7
            - extract(dow from first_day)::int
            as first_day
        from first_month_day
    ), first_next_month_day as (
        select (first_day + interval '1 month')::date as first_day
        from first_month_day
    ), last_business_day as (
        select
            first_day
            + 6
            - extract(dow from first_day)::int
            as last_day
        from first_next_month_day
    )
    select
        (select first_day from first_business_day) as first_day,
        (select last_day from last_business_day) as last_day
    ;
$$ language sql stable;

测试

select
    to_char(d, 'YYYY Month') as month,
    to_char(first_day, 'YYYY-MM-DD Day') as first_day,
    to_char(last_day, 'YYYY-MM-DD Day') as last_day
from
    generate_series ('2010-01-01'::date, '2014-12-31', '1 month') g (d)
    ,
    business_month(d::date)
;