Search code examples
sqlcasesybasedatediffsap-iq

Case statement with datedfif and between


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' 

Solution

  • 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'