按某些字段的值进行组选择

时间:2015-09-12 19:57:03

标签: sql sql-server

我有以下选择:

| EmployeeId | DepartmentName | Salary |
----------------------------------------
| 1          | A              | 10     |
| 2          | A              | 10     |
| 3          | A              | 15     |
| 4          | A              | 20     |
| 5          | A              | 20     |
| 6          | B              | 15     |
| 7          | B              | 25     |
| 8          | B              | 25     |

我想按行/ 中的工资对所有行进行分组,并将此数量的组添加到选择中。

结果选择示例:

| EmployeeId | DepartmentName | Salary | Group |
------------------------------------------------
| 1          | A              | 10     | 1     |
| 2          | A              | 10     | 1     |
| 3          | A              | 15     | 2     |
| 4          | A              | 20     | 3     |
| 5          | A              | 20     | 3     |
| 6          | B              | 15     | 1     |
| 7          | B              | 25     | 2     |
| 8          | B              | 25     | 2     |

1 个答案:

答案 0 :(得分:2)

SELECT * 
      , DENSE_RANK() OVER (PARTITION BY DepartmentName
                           ORDER BY Salary) AS [Group]
FROM TableName