If we want to order the data differently for per group, we can add a CASE
syntax to the ORDER BY
.
In this example, we want to order employees from Department 1 by last name and employees from Department 2 by salary.
Id | FName | LName | PhoneNumber | ManagerId | DepartmentId | Salary | HireDate |
---|---|---|---|---|---|---|---|
1 | James | Smith | 1234567890 | NULL | 1 | 1000 | 01-01-2002 |
2 | John | Johnson | 2468101214 | 1 | 1 | 400 | 23-03-2005 |
3 | Michael | Williams | 1357911131 | 1 | 2 | 600 | 12-05-2009 |
4 | Johnathon | Smith | 1212121212 | 2 | 1 | 500 | 24-07-2016 |
5 | Sam | Saxon | 1372141312 | 2 | 2 | 400 | 25-03-2015 |
The following query will provide the required results:
SELECT Id, FName, LName, Salary FROM Employees
ORDER BY Case When DepartmentId = 1 then LName else Salary end