Skip to content
Advertisement

Using CASE WHEN to assign buckets

Fairly new to coding. I’ve created a new column that outputs the days a task is overdue using DateDiff. I then want to take the result of the DateDiff and assign it an expression (>60 days overdue, 30-45 days overdue, etc.) using CASE WHEN. However, this errors out, specifically saying that there’s an “Incorrect syntax near the keyword ‘CASE”

SELECT t.name, t.Task,DateDiff(day, t.DueDate, GetDate()) As DaysOverdue
CASE WHEN DaysOverdue >= 60 THEN '>60 days Overdue'
     WHEN DaysOverdue <=45 And >=30 THEN '30-45 days Overdue'
     ELSE 'Current' END as bucket
FROM t

I want it to create a new column called ‘bucket’ that shows the result of the CASE WHEN expression

name   task      Daysoverdue         bucket

  x       y            43            30-45 days overdue
  a       b            64            >60 days overdue

Advertisement

Answer

You have missed a comma (,) after DaysOverdue

also do not use DaysOverdue alias in the case, use DateDiff(day, t.DueDate, GetDate())

you cannot use > and < this way WHEN DaysOverdue <=45 And >=30 instead use

WHEN DateDiff(day, t.DueDate, GetDate()) between 30 And 45

This is how it should be in the end

SELECT t.name, t.Task,DateDiff(day, t.DueDate, GetDate()) As DaysOverdue,
CASE WHEN DateDiff(day, t.DueDate, GetDate())>= 60 THEN '>60 days Overdue'
     WHEN DateDiff(day, t.DueDate, GetDate()) between 30 And 45 THEN '30-45 days Overdue'
     ELSE 'Current' END as bucket
FROM t
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement