We can use expressions as well in Order by clause. Suppose we want to sort for a year in a date column. Let us run the query without any Order by clause first.
SELECT top 10 [NationalIDNumber]
, SickLeaveHours as [SickHours]
,[Vacationhours]
,[BirthDate]
,[MaritalStatus]
,[Gender]
,[ModifiedDate]
,[SalariedFlag]
FROM [AdventureWorks2017].[HumanResources].[Employee]
Where MaritalStatus='M'
Now, we want to sort on Birthdate column yearly in ascending order. I am using the TOP clause to limit result in the output. We are using DATEPART function we get a specified part of a date. In this query, we want to extract year to sort data using the DATEPART function.
1
2
3
4
5
6
7
8
9
10
11 |
SELECT top 10 [NationalIDNumber]
, SickLeaveHours as [SickHours]
,[Vacationhours]
,[BirthDate]
,[MaritalStatus]
,[Gender]
,[ModifiedDate]
,[SalariedFlag]
FROM [AdventureWorks2017].[HumanResources].[Employee]
Where MaritalStatus='M'
Order by DATEPART(YEAR , BirthDate) ASC |