回合日期到下个月的第一天

时间:2018-02-21 22:32:08

标签: sql amazon-redshift

以下查询需要mean并提供应用月份的最后一天(numcolwise)和应用周的星期日(application_date):

cohort

这适用于我想要做的事情,但是在first_week<>月份的情况下select cast(last_day(application_date) as date) end as cohort, cast(dateadd(day, -(datepart(dow, application_date)), application_date) as date) first_week from table 月,我想将cohort舍入到下个月的第一天(= first_week个月)。

当前输出示例:

first_week

预期产出:

cohort

谢谢!

1 个答案:

答案 0 :(得分:0)

Case Statement逻辑读为

1)如果上一个星期日是上个月,则获取申请日期的第一天,这是您的第一周。
2)如果申请日期不是星期日,则在申请日期之前获得星期日,而不是上个月。

declare @mytable table (application_date date,cohort date)
insert into @mytable
values
('1/2/18','1/31/18'),  -- 1/1/18
('1/5/18','1/31/18'),  -- 1/1/18
('1/7/18','1/31/18'), -- 1/7/18
('1/13/18','1/31/18'), -- 1/7/18
('2/1/18','2/28/18'),  -- 2/1/18   
('2/27/18','2/28/18')  -- 2/25/18   


select *,

case when 
        month(
         case when datepart(dw,application_date)=1 then  application_date
         else dateadd(day,(-1*datepart(dw,application_date))+1,application_date)
         end

   ) <> month(application_date) then
      cast(concat(year(application_date),right('0' + cast(month(application_date) as varchar(20)),2),'01') as date)
    else
       case when datepart(dw,application_date)=1 then 
              application_date
       else 
           dateadd(day,(-1*datepart(dw,application_date))+1,application_date)
       end
   end     firstweek

from @mytable