Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 872
Dawood Zaidi Avatar asked Jun 14 '26 20:06

Dawood Zaidi


2 Answers

For greater query efficiency I would avoid the format() approach.

select
       left(datename(month,[Date]),3) [Month]
     , year([Date]) [Year]
     , [Tickets Generated]
from (
        SELECT
               dateadd(month,datediff(month,0,t.[Date]),0) as [Date]
             , COUNT(*) as [Tickets Generated]
        FROM [SambaData2].[dbo].[Tickets] AS t
        GROUP BY dateadd(month,datediff(month,0,t.[Date]),0)
    ) as d
ORDER BY [Date]

The core to this approach is the following:

dateadd(month,datediff(month,0,t.[Date]),0)

this has the effect of locating the first day of the relevant year & month, thus leaving a whole date available for the order by clause, but still grouping to the required level. Runing the foillowing may help explain

select 
  datediff(month,0,getdate()) a
, dateadd(month,datediff(month,0,getdate()),0) b
, left(datename(month,getdate()),3) c
, getdate() d


   a          b        c              d           
 ------- ------------ ----- --------------------- 
  1425    2018-10-01   Oct   2018-10-04 08:08:19     
like image 189
Paul Maxwell Avatar answered Jun 17 '26 03:06

Paul Maxwell


Here is another option:

SELECT
    FORMAT(Date, 'yyy') AS Year,
    FORMAT(Date, 'MMM') AS Date,
    COUNT(*) AS [Tickets Generated]
FROM [SambaData2].[dbo].[Tickets]
GROUP BY
    FORMAT(Date, 'yyy'),
    FORMAT(Date, 'MMM')
ORDER BY
    TRY_CONVERT(datetime, FORMAT(Date, 'yyy') + '-' + FORMAT(Date, 'MMM'));

I prefer this method over the accepted answer because it is only uses components in the ORDER BY clause which were actually present in the SELECT clause. Certain RDBMS would complain about an ORDER BY using components not present in SELECT. This answer also assumes that your version of SQL Server supports TRY_CONVERT.

like image 27
Tim Biegeleisen Avatar answered Jun 17 '26 03:06

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!