如果员工的薪水最高为5000,则等级= 1,最高为100k,则等级= 2,依此类推。我们可以使用等级函数得到结果吗?

时间:2019-05-23 10:49:43

标签: sql-server ranking-functions

如果雇员的薪水低于50,000,则等级= 1,最高为100000,然后等级2,最高为150000,然后为等级3。

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

2 个答案:

答案 0 :(得分:1)

从您的评论看来,您似乎只需要一种方法来计算50,000的时间间隔的排名,因此您不必使用连续的CASE表达式。使用简单的整数除法而不是RANK函数就可以很容易地做到这一点:

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

为您提供以下结果:

+-----+-----------+-----+
| 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 |
+-----+-----------+-----+

如果需要,您还可以根据需要将其添加为计算列(并为其编制索引)。

答案 1 :(得分:0)

您的语法不正确,应该使用CASE

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