sqlsql-serversortingt-sql

Sort Month Name in SQL Query


My Current Query is :

SELECT FORMAT(Date, 'MMM') as 'Date', FORMAT(Date, 'yyy') as 'Year' 
,COUNT(*) 
as 'Tickets Generated'
FROM [SambaData2].[dbo].[Tickets]
GROUP BY FORMAT(Date, 'MMM'), FORMAT(Date, 'yyy')
ORDER BY Date

It returns the values:

enter image description here

I would like the same query to return sorted month name with Year!


Solution

  • Use year(date), month(date) in order by month() function will give you month number so you can order it easily

    SELECT FORMAT(Date, 'MMM') as 'Date', FORMAT(Date, 'yyy') as 'Year',
    COUNT(*) 
    as 'Tickets Generated'
    FROM [SambaData2].[dbo].[Tickets]
    GROUP BY FORMAT(Date, 'MMM'), FORMAT(Date, 'yyy'),year(Date),month(Date)
    ORDER BY year(Date),month(Date)