-2

I am using Sybase IQ, and have the following SQL code which doesn't seem to work. The issue is with the case statement.. Thanks in advance

SELECT  a.cusid, start_date, effective_dt, 
case when DATEDIFF(DAY, start_date, effective_dt) >= 5476 THEN 'Green'
case when DATEDIFF(DAY, start_date, effective_dt) between 2921 AND 4575 THEN 'Red'
case when DATEDIFF(DAY, start_date, effective_dt) BETWEEN 1096  AND 2920 THEN 'Blue'
case when DATEDIFF(DAY, start_date, effective_dt) BETWEEN 0 AND 1095 THEN 'Rose'
ELSE NULL END as tier
FROM   tablea a
INNER JOIN tableb b
    ON a.cusid = b.cusid
WHERE   b.active = 'Yes' 
Liam
  • 27,717
  • 28
  • 128
  • 190
Nick Edwards
  • 55
  • 1
  • 10
  • 1
    *doesn't seem to work* doesn't work how? – Liam Nov 28 '17 at 10:43
  • 1
    "doesn't seem to work" is not a problem description. Do you get errors? What are the errors? Do you get unexpected results? What do you expect, and what are the actual results? – HoneyBadger Nov 28 '17 at 10:44

2 Answers2

2

No need to have case keyword each time with when clause. Try this :

SELECT  a.cusid, start_date, effective_dt, 
case when DATEDIFF(DAY, start_date, effective_dt) >= 5476 THEN 'Green'
when DATEDIFF(DAY, start_date, effective_dt) between 2921 AND 4575 THEN 'Red'
when DATEDIFF(DAY, start_date, effective_dt) BETWEEN 1096  AND 2920 THEN 'Blue'
when DATEDIFF(DAY, start_date, effective_dt) BETWEEN 0 AND 1095 THEN 'Rose'
ELSE NULL END as tier
FROM   tablea a
INNER JOIN tableb b
    ON a.cusid = b.cusid
WHERE   b.active = 'Yes'
Nikhil Shetkar
  • 346
  • 1
  • 9
1

You have the syntax slightly off. You don't need to the case for each condition:

SELECT  a.cusid, start_date, effective_dt, 
CASE when DATEDIFF(DAY, start_date, effective_dt) >= 5476 THEN 'Green'
     when DATEDIFF(DAY, start_date, effective_dt) between 2921 AND 4575 THEN 'Red'
     when DATEDIFF(DAY, start_date, effective_dt) BETWEEN 1096  AND 2920 THEN 'Blue'
     when DATEDIFF(DAY, start_date, effective_dt) BETWEEN 0 AND 1095 THEN 'Rose'
  ELSE NULL END as tier
FROM   tablea a
INNER JOIN tableb b
    ON a.cusid = b.cusid
WHERE   b.active = 'Yes' 
cf_en
  • 1,661
  • 1
  • 10
  • 18