简体   繁体   中英

Round date to first day of next month

The following query takes application_date and gives the last day of the month of application ( cohort ), and the Sunday of the week of application ( 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

This works perfectly for what I am trying to do, however in cases where month of cohort <> month of first_week , then I would like to round first_week to the first day of the next month (= cohort month).

Current output example:

application_date   cohort   first week
1/2/18             1/31/18  1/31/17
1/5/18             1/31/18  1/31/17
1/7/18             1/31/18  1/7/18
1/13/18            1/31/18  1/7/18
2/1/18             2/28/18  1/28/18     

Expected output:

application_date   cohort   first week
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   

Thank you!

Case Statement logic read as

1) If the last sunday is of the previous month then get the 1st day of the application date and this is your first week.
2) If the application date is not a sunday then get the sunday date before the application date which is not from the previous month.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM