-1

If salary of employee is below 50,000 then rank = 1, up to 100 000 then rank 2, up to 150 000 then rank 3.Can I get this using rank function?

SELECT CASE WHEN SALARY BETWEEN 1 , 50000 then 1 
else case when salary between 50000 , 100000 then 2
else case when salary between 150000 , 200000 then 3 else 4 end as rank FROM EMPLOYEE WHERE EMP = 1
James Z
  • 12,209
  • 10
  • 24
  • 44

2 Answers2

1

From your comments, it seems that you just need a way to calculate the rank for intervals of 50,000, so you don't have to use successive CASE expressions. This can be done easily enough using simple integer division, rather than the RANK function:

SELECT *, CAST(salary / 50000 AS INT) + 1 AS Rnk
FROM Employee

gives you these results:

+-----+-----------+-----+
| emp |  salary   | rnk |
+-----+-----------+-----+
|   1 |  49000.00 |   1 |
|   2 |  50000.00 |   2 |
|   3 |  99000.00 |   2 |
|   4 | 100000.00 |   3 |
|   5 | 149000.00 |   3 |
|   6 | 150000.00 |   4 |
+-----+-----------+-----+

If desired, you could also add this as a calculated column (and index it) as desired.

Zack
  • 2,220
  • 1
  • 8
  • 12
0

Your syntax is incorrect, there is how CASE should be used:

SELECT 
    CASE 
        WHEN salary BETWEEN 1 AND 49999 THEN 1 
        WHEN salary BETWEEN 50000 AND 99999 THEN 2
        WHEN salary BETWEEN 100000 AND 150000 THEN 3 
        ELSE 4 
    END AS rnk 
FROM EMPLOYEE 
WHERE EMP = 1 -- I'm not sure what you trying to filter here