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:

I would like the same query to return sorted month name with Year!
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With