Home > Software design >  CASE statement with the changing dates
CASE statement with the changing dates

Time:03-15

Namely what I need is:

The key over here is that it does change the dates every week, from last Sunday, to 2nd last Sunday and so on, so that it is dynamic.

Will appreciate if someone can help.

CASE
  WHEN f.[STARTDATE] = last week Sunday (03/06) THEN '1 week ago'
  WHEN f.[STARTDATE] = last 2 week Sunday (02/27) THEN '2 weeks ago'
  WHEN f.[STARTDATE] = last 3 week Sunday (02/20) THEN '3 week ago'
  WHEN f.[STARTDATE] = last 4 week Sunday (02/13) THEN '4 week ago'
END AS 'STARTDATE'

Thank you

CodePudding user response:

First you need to get nearest Sunday before you can subtract 7, 14, 21 and 28 days from it. The simplest way is to check current day of week and calculate an offset: 0 for Sunday, 1 for Monday and so on:

with cte as (
select offsett = case datename(weekday, cast(current_timestamp as date))
    when 'sunday'    then 0
    when 'monday'    then 1
    when 'tuesday'   then 2
    when 'wednesday' then 3
    when 'thursday'  then 4
    when 'friday'    then 5
    when 'saturday'  then 6
end
)
select case
    when f.[startdate] = dateadd(day, -cte.offsett -  7, cast(current_timestamp as date)) then '1 week ago'
    when f.[startdate] = dateadd(day, -cte.offsett - 14, cast(current_timestamp as date)) then '2 week ago'
    -- ...
end
from f
cross join cte
  • Related