Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Hi, I have the follwoing query which gives the results as shown;
SELECT CASE Month(RegistrationDate) WHEN 1 THEN 'Jan' WHEN 2 THEN 'Feb' WHEN 3 THEN 'Mar' WHEN 4 THEN 'Apr' WHEN 5 THEN 'May' WHEN 6 THEN 'Jun' WHEN 7 THEN 'Jul' WHEN 8 THEN 'Aug' WHEN 9 THEN 'Sep' WHEN 10 THEN 'Oct' WHEN 11 THEN 'Nov' WHEN 12 THEN 'Dec' END AS Month, YEAR(RegistrationDate) AS Year, COUNT(*) AS TotalFROM dbo.aspnet_cprdContactsGROUP BY MONTH(RegistrationDate), YEAR(RegistrationDate)
Results:Month Year Total Apr 2012 168Jan 2014 56May 2013 67Sep 2012 11Oct 2013 100Feb 2014 45Now, I want my result to be; Month Year Total Apr 2012 168Sep 2012 11May 2013 67Oct 2013 100Jan 2014 56Feb 2014 45Any help highly appreciated.. Thanks
khtan
In (Som, Ni, Yak)
17689 Posts
Posted - 2014-03-24 : 08:01:48
[code]ORDER BY YEAR(RegistrationDate), MONTH(RegistrationDate)[/code]also you don't need the case when to get the month name. [code]SELECT LEFT(DATENAME(MONTH, RegistrationDate), 3) AS [Month], YEAR(RegistrationDate) AS [Year], COUNT(*) AS TotalFROM dbo.aspnet_cprdContactsGROUP BY YEAR(RegistrationDate), MONTH(RegistrationDate) ORDER BY YEAR(RegistrationDate), MONTH(RegistrationDate) [/code]KH[spoiler]Time is always against us[/spoiler]
dr223
Constraint Violating Yak Guru
444 Posts
Posted - 2014-03-24 : 08:22:56
In SQL I receive the error message; Column 'dbo.aspnet_cprdContacts.RegistrationDate' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
khtan
In (Som, Ni, Yak)
17689 Posts
Posted - 2014-03-24 : 08:43:29
sorry . .
SELECT LEFT(DATENAME(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, RegistrationDate), 0)), 3) AS [Month], YEAR(DATEADD(MONTH, DATEDIFF(MONTH, 0, RegistrationDate), 0)) AS [Year], COUNT(*) AS TotalFROM dbo.aspnet_cprdContactsGROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, RegistrationDate), 0)ORDER BY [Year], [Month]