July 26, 2010 at 2:35 pm
Hi,
I've been searching to do this but haven't found the answer, the closer I can go is ordering by proper month but instead of showing the month name it gives it to me in numbers lik (1, 2, 3, 4) I want (january, february, march)
Here is what Ive done so far
To get the name of the month one part of my query says
datename(month, date) as month
then I'm trying to order it like
ORDER BY month
but the result ends up ordering the month in alphabetical order.
Any ideas?
Thanks
July 26, 2010 at 2:42 pm
With "Order by" it does not need to be something in your select list.
So you can select datename(month,YOURFIELD) and order by datepart(month,YOURFIELD)
July 26, 2010 at 3:02 pm
Hi,
The thing is that the query I use has a GROUP BY clause because it has to get data from different referenced tables. In fact I'm grouping by months, but these ones come ordered alphabetically.
What can I do?
July 26, 2010 at 3:08 pm
For a GROUP BY query, you can only order by columns in the SELECT list. Therefore the only way to do what you need is to put the month datepart into the select list and order by that number. You can't do it by the alphanumeric name.
July 26, 2010 at 3:42 pm
Mmmm... that's sad
I guess I will use a temp table or something like that, thanks
July 26, 2010 at 3:55 pm
Can you use a subquery?
SELECT
Field1, Field2 FROM
(
Your query here with your groupings
) AS MyAlias
ORDER BY whatever you want
This is of course air code and not guaranteed to work...
July 26, 2010 at 4:57 pm
In this example, I group by the first day of the month, order by that value, and extract year and month from that value.
select
[Year]= year(dateadd(mm,datediff(mm,0,Mydate),0)),
MonthName= datename(month,dateadd(mm,datediff(mm,0,Mydate),0)),
[RowCount]= count(*)
from
( -- Random Test Dates
select top 1000 mydate = crdate from sysobjects order by newid()
) a
group by
dateadd(mm,datediff(mm,0,Mydate),0)
order by
dateadd(mm,datediff(mm,0,Mydate),0)
Results:
Year MonthName RowCount
----------- ------------------------------ -----------
2003 April 1
2005 October 46
2007 November 46
2008 March 39
2008 September 36
2010 April 71
2010 May 13
2010 June 13
2010 July 9
(9 row(s) affected)
July 27, 2010 at 6:07 am
hi,
try the following query
SELECT DATENAME(month, GETDATE()) AS 'Month Name'
Viewing 8 posts - 1 through 7 (of 7 total)
You must be logged in to reply to this topic. Login to reply