Order by for Month Names

Samooramad
Samooramad used Ask the Experts™
on
Hi Experts,

I have the following query which works fine. I just need to figure out how to sort by Month order instead of having months sorted alphabetically. I'm sure there is a simple way to do this but I can't think of anything.

Appreciate your help

Query is:


SELECT  DATENAME(MM,[SubmissionDate]) as  MonthName
            ,DATEPART(YEAR,[SubmissionDate]) as YearName
            ,SUM(CASE R.BranchID WHEN 1 THEN 1 ELSE 0 END) Riyadh
            ,SUM(CASE R.BranchID WHEN 2 THEN 1 ELSE 0 END)  Jeddah
            ,SUM(CASE R.BranchID WHEN 3 THEN 1 ELSE 0 END)  Dammam
            ,SUM(CASE WHEN R.BranchID ='1' OR R.BranchID ='2' OR R.BranchID ='3' THEN 1 ELSE 0 END) as  Total

FROM [STR].[dbo].[ILicensesRenewApplications]R
WHERE StatusID <> 1
Group by DATENAME(MM,[SubmissionDate]),DATEPART(YEAR,[SubmissionDate])

UNION
SELECT  'Sum'  MonthName
            ,' ' YearName
            ,SUM(CASE R.BranchID WHEN 1 THEN 1 ELSE 0 END)  Riyadh
            ,suM(CASE R.BranchID WHEN 2 THEN 1 ELSE 0 END)  Jeddah
            ,SUM(CASE R.BranchID WHEN 3 THEN 1 ELSE 0 END)   Dammam
            ,SUM(CASE WHEN R.BranchID ='1' OR R.BranchID ='2' OR R.BranchID ='3' THEN 1 ELSE 0 END) as Total

FROM [STR].[dbo].[ILicensesRenewApplications]R
WHERE StatusID <> 1
order by MonthName, YearName



screenshot of output
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Steve WalesSenior Database Administrator

Commented:
Change your

order by MonthName, YearName

to:

order by DATEPART(MM,[SubmissionDate]), YearName

That should do the trick (tested on SQL Server 2005)

Author

Commented:
Already tried that. I get this error when I do that:

Msg 104, Level 16, State 1, Line 22
ORDER BY items must appear in the select list if the statement contains a UNION, INTERSECT or EXCEPT operator.
Steve WalesSenior Database Administrator

Commented:
Just tested something similar, which should work when applied to your query

Loaded a table of dates:

create table tab2 (date datetime)

insert into tab2 values ('20120101')
insert into tab2 values ('20120201')
insert into tab2 values ('20120301')
insert into tab2 values ('20120401')
insert into tab2 values ('20120501')
insert into tab2 values ('20120601')
insert into tab2 values ('20120701')
insert into tab2 values ('20120801')
insert into tab2 values ('20120901')
insert into tab2 values ('20121001')
insert into tab2 values ('20121101')
insert into tab2 values ('20121201')

Open in new window


This query produced the same error:

select datename(MM, date) as month_name 
from tab2 
union
select datename(MM, date) as month_name 
from tab2
order by datepart(mm, [date])

Open in new window


However, modify it like this and it works just fine:

select datename(MM, month_name) as month_name 
from
(
select date as month_name 
from tab2 
union
select date as month_name 
from tab2 ) as a
order by datepart(mm, [month_name])

Open in new window


Apply the same concept to your query and it should work.

Inner query with the union just lists the date, then select from the inner query, do the datename/datepart functions and apply the order by to that.
Success in ‘20 With a Profitable Pricing Strategy

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Imran Javed ZiaConsultant Software Engineer - .NET Architect

Commented:
for simple query you can Add following in Order by clause
MONTH(SubmissionDate)

and for your query, justy add month Number in your query and then then order by that column
Ephraim WangoyaSoftware Engineer

Commented:
You can order using a case statement
SELECT  DATENAME(MM,[SubmissionDate]) as  MonthName
			,DATEPART(YEAR,[SubmissionDate]) as YearName
			,SUM(CASE R.BranchID WHEN 1 THEN 1 ELSE 0 END) Riyadh
			,SUM(CASE R.BranchID WHEN 2 THEN 1 ELSE 0 END)  Jeddah
			,SUM(CASE R.BranchID WHEN 3 THEN 1 ELSE 0 END)  Dammam
			,SUM(CASE WHEN R.BranchID ='1' OR R.BranchID ='2' OR R.BranchID ='3' THEN 1 ELSE 0 END) as  Total

FROM [STR].[dbo].[ILicensesRenewApplications]R
WHERE StatusID <> 1
Group by DATENAME(MM,[SubmissionDate]),DATEPART(YEAR,[SubmissionDate])
UNION 
SELECT  'Sum'  MonthName
            ,' ' YearName
            ,SUM(CASE R.BranchID WHEN 1 THEN 1 ELSE 0 END)  Riyadh
            ,suM(CASE R.BranchID WHEN 2 THEN 1 ELSE 0 END)  Jeddah
            ,SUM(CASE R.BranchID WHEN 3 THEN 1 ELSE 0 END)   Dammam
            ,SUM(CASE WHEN R.BranchID ='1' OR R.BranchID ='2' OR R.BranchID ='3' THEN 1 ELSE 0 END) as Total

FROM [STR].[dbo].[ILicensesRenewApplications]R
WHERE StatusID <> 1
order by case MonthName
			when 'January' then 1
			when 'February' then 2
			when 'March' then 3
			when 'April' then 4
			when 'May' then 5
			when 'June' then 6
			when 'July' then 7
			when 'August' then 8
			when 'September' then 9
			when 'October' then 10
			when 'November' then 11
			when 'December' then 12
			else 13
		end, 
		YearName

Open in new window

Software Engineer
Commented:
Correction, make it a subquery

SELECT *
FROM
(
	SELECT  DATENAME(MM,[SubmissionDate]) as  MonthName
				,DATEPART(YEAR,[SubmissionDate]) as YearName
				,SUM(CASE R.BranchID WHEN 1 THEN 1 ELSE 0 END) Riyadh
				,SUM(CASE R.BranchID WHEN 2 THEN 1 ELSE 0 END)  Jeddah
				,SUM(CASE R.BranchID WHEN 3 THEN 1 ELSE 0 END)  Dammam
				,SUM(CASE WHEN R.BranchID ='1' OR R.BranchID ='2' OR R.BranchID ='3' THEN 1 ELSE 0 END) as  Total

	FROM [STR].[dbo].[ILicensesRenewApplications]R
	WHERE StatusID <> 1
	Group by DATENAME(MM,[SubmissionDate]),DATEPART(YEAR,[SubmissionDate])
	UNION 
	SELECT  'Sum'  MonthName
				,' ' YearName
				,SUM(CASE R.BranchID WHEN 1 THEN 1 ELSE 0 END)  Riyadh
				,suM(CASE R.BranchID WHEN 2 THEN 1 ELSE 0 END)  Jeddah
				,SUM(CASE R.BranchID WHEN 3 THEN 1 ELSE 0 END)   Dammam
				,SUM(CASE WHEN R.BranchID ='1' OR R.BranchID ='2' OR R.BranchID ='3' THEN 1 ELSE 0 END) as Total

	FROM [STR].[dbo].[ILicensesRenewApplications]R
	WHERE StatusID <> 1
) A	
order by case MonthName
			when 'January' then 1
			when 'February' then 2
			when 'March' then 3
			when 'April' then 4
			when 'May' then 5
			when 'June' then 6
			when 'July' then 7
			when 'August' then 8
			when 'September' then 9
			when 'October' then 10
			when 'November' then 11
			when 'December' then 12
			else 13
		end, 
		YearName

Open in new window

Top Expert 2012

Commented:
Try it this way (notice how I also reversed the order of the year and month):
SELECT  MonthName,
        YearName,
        Riyadh,
        Jeddah,
        Dammam,
        Total
FROM    (SELECT DATEPART(YEAR, [SubmissionDate]) AS YearName,
                DATEPART(MM, [SubmissionDate]) MonthNumber,
                DATENAME(MM, [SubmissionDate]) AS MonthName,
                SUM(CASE R.BranchID
                      WHEN 1 THEN 1
                      ELSE 0
                    END) Riyadh,
                SUM(CASE R.BranchID
                      WHEN 2 THEN 1
                      ELSE 0
                    END) Jeddah,
                SUM(CASE R.BranchID
                      WHEN 3 THEN 1
                      ELSE 0
                    END) Dammam,
                SUM(CASE WHEN R.BranchID = '1'
                              OR R.BranchID = '2'
                              OR R.BranchID = '3' THEN 1
                         ELSE 0
                    END) AS Total
         FROM   [STR].[dbo].[ILicensesRenewApplications] R
         WHERE  StatusID <> 1
         GROUP BY DATEPART(year, [SubmissionDate]),
                DATEPART(month, [SubmissionDate]),
                DATENAME(month, [SubmissionDate])
         UNION ALL
         SELECT 9999 YearName,
                13,
                'Sum' MonthName,
                SUM(CASE R.BranchID
                      WHEN 1 THEN 1
                      ELSE 0
                    END) Riyadh,
                SUM(CASE R.BranchID
                      WHEN 2 THEN 1
                      ELSE 0
                    END) Jeddah,
                SUM(CASE R.BranchID
                      WHEN 3 THEN 1
                      ELSE 0
                    END) Dammam,
                SUM(CASE WHEN R.BranchID = '1'
                              OR R.BranchID = '2'
                              OR R.BranchID = '3' THEN 1
                         ELSE 0
                    END) AS Total
         FROM   [STR].[dbo].[ILicensesRenewApplications] R
         WHERE  StatusID <> 1
        ) x
ORDER BY YearName,
        MonthNumber

Open in new window

Author

Commented:
sjwales,

sorry I'm lost. Could you explain how I need to modify my query in order to avoid the error?
Steve WalesSenior Database Administrator

Commented:
Basically what you want to do is do a select from a select.

I don't have your exact database layout to play with but something fairly close to this should work:

SELECT  DATENAME(MM,[SubmissionDate]) as  MonthName
            ,DATEPART(YEAR,[SubmissionDate]) as YearName
            ,Riyadh
            ,Jeddah
            ,Dammam
            ,Total
FROM
(
SELECT  [SubmissionDate] as  MonthName
            ,[SubmissionDate] as YearName
            ,SUM(CASE R.BranchID WHEN 1 THEN 1 ELSE 0 END) Riyadh
            ,SUM(CASE R.BranchID WHEN 2 THEN 1 ELSE 0 END)  Jeddah
            ,SUM(CASE R.BranchID WHEN 3 THEN 1 ELSE 0 END)  Dammam
            ,SUM(CASE WHEN R.BranchID ='1' OR R.BranchID ='2' OR R.BranchID ='3' THEN 1 ELSE 0 END) as  Total

FROM [STR].[dbo].[ILicensesRenewApplications]R
WHERE StatusID <> 1
Group by DATENAME(MM,[SubmissionDate]),DATEPART(YEAR,[SubmissionDate])

UNION
SELECT  'Sum'  MonthName
            ,' ' YearName
            ,SUM(CASE R.BranchID WHEN 1 THEN 1 ELSE 0 END)  Riyadh
            ,suM(CASE R.BranchID WHEN 2 THEN 1 ELSE 0 END)  Jeddah
            ,SUM(CASE R.BranchID WHEN 3 THEN 1 ELSE 0 END)   Dammam
            ,SUM(CASE WHEN R.BranchID ='1' OR R.BranchID ='2' OR R.BranchID ='3' THEN 1 ELSE 0 END) as Total

FROM [STR].[dbo].[ILicensesRenewApplications]R
WHERE StatusID <> 1
) as a
order by DATEPART(MM,[SubmissionDate])
            ,DATEPART(YEAR,[SubmissionDate]) 

Open in new window


You have your base query as the "inner" query that does the majority of the work, executing your CASE statements and doing the UNION and filtering on the StatusID but returning the date twice (although, you could actually only return it once and then select it twice in the outer select - either way works).

That then returns a result set that you can select from again and perform your order by manipulations on.

The inner query is returning a basic date.  All you do then is select all of the results and manipulate the date returned to show you names in the query but order by their actual place in the year.
Scott PletcherSenior DBA
Most Valuable Expert 2018
Top Expert 2014

Commented:
SELECT
    CASE WHEN SubmissionDate IS NULL THEN 'Sum' ELSE DATENAME(MONTH,[SubmissionDate]) END AS MonthName,
    CASE WHEN SubmissionDate IS NULL THEN ' ' ELSE DATEPART(YEAR, [SubmissionDate]) END AS YearName,
    Riyadh,
    Jeddah,
    Dammam,
    [Total]    
FROM (
      SELECT  
                         DATEADD(MONTH, DATEDIFF(MONTH, 0, [SubmissionDate]), 0) AS SubmissionDate
                        ,SUM(CASE R.BranchID WHEN 1 THEN 1 ELSE 0 END) AS Riyadh
                        ,SUM(CASE R.BranchID WHEN 2 THEN 1 ELSE 0 END) AS Jeddah
                        ,SUM(CASE R.BranchID WHEN 3 THEN 1 ELSE 0 END) AS Dammam
                        ,SUM(CASE WHEN R.BranchID ='1' OR R.BranchID ='2' OR R.BranchID ='3' THEN 1 ELSE 0 END) AS [Total]
      FROM [STR].[dbo].[ILicensesRenewApplications]
      WHERE StatusID <> 1 AND R.BranchID IN (1, 2, 3)
      GROUP BY     DATEADD(MONTH, DATEDIFF(MONTH, 0, [SubmissionDate]), 0) WITH ROLLUP
) AS derived_table
ORDER BY
    MONTH([SubmissionDate]),
    YEAR([SubmissionDate])

Commented:
you mentioned that

"how to sort by Month order instead of having months sorted alphabetically"

means you want to sort result by month number instead of monthname..

if so you must use "DATEPART(mm,CAST(MonthName + ' 1, 1900' AS DATETIME)) " instead of "monthname" in your order by clause try below query might helps you...


SELECT  DATENAME(MM,[SubmissionDate]) as  MonthName
            ,DATEPART(YEAR,[SubmissionDate]) as YearName
            ,SUM(CASE R.BranchID WHEN 1 THEN 1 ELSE 0 END) Riyadh
            ,SUM(CASE R.BranchID WHEN 2 THEN 1 ELSE 0 END)  Jeddah
            ,SUM(CASE R.BranchID WHEN 3 THEN 1 ELSE 0 END)  Dammam
            ,SUM(CASE WHEN R.BranchID ='1' OR R.BranchID ='2' OR R.BranchID ='3' THEN 1 ELSE 0 END) as  Total

FROM [STR].[dbo].[ILicensesRenewApplications]R
WHERE StatusID <> 1
Group by DATENAME(MM,[SubmissionDate]),DATEPART(YEAR,[SubmissionDate])

UNION
SELECT  'Sum'  MonthName
            ,' ' YearName
            ,SUM(CASE R.BranchID WHEN 1 THEN 1 ELSE 0 END)  Riyadh
            ,suM(CASE R.BranchID WHEN 2 THEN 1 ELSE 0 END)  Jeddah
            ,SUM(CASE R.BranchID WHEN 3 THEN 1 ELSE 0 END)   Dammam
            ,SUM(CASE WHEN R.BranchID ='1' OR R.BranchID ='2' OR R.BranchID ='3' THEN 1 ELSE 0 END) as Total

FROM [STR].[dbo].[ILicensesRenewApplications]R
WHERE StatusID <> 1
order by DATEPART(mm,CAST(MonthName + ' 1, 1900' AS DATETIME)) , YearName

Author

Commented:
sjwales,

sorry for delay. I tried your posted solution and still get errors:

Msg 8120, Level 16, State 1, Line 9
Column 'STR.dbo.ILicensesRenewApplications.SubmissionDate' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'SubmissionDate'.
Msg 207, Level 16, State 1, Line 2
Invalid column name 'SubmissionDate'.
Msg 207, Level 16, State 1, Line 31
Invalid column name 'SubmissionDate'.
Msg 207, Level 16, State 1, Line 32
Invalid column name 'SubmissionDate'.

Author

Commented:
ewangoya,

I tried your first post and got this error:

Msg 207, Level 16, State 1, Line 21
Invalid column name 'MonthName'.
Msg 207, Level 16, State 1, Line 21
Invalid column name 'MonthName'.
Msg 207, Level 16, State 1, Line 21
Invalid column name 'MonthName'.
Msg 207, Level 16, State 1, Line 21
Invalid column name 'MonthName'.
Msg 207, Level 16, State 1, Line 21
Invalid column name 'MonthName'.
Msg 207, Level 16, State 1, Line 21
Invalid column name 'MonthName'.
Msg 207, Level 16, State 1, Line 21
Invalid column name 'MonthName'.
Msg 207, Level 16, State 1, Line 21
Invalid column name 'MonthName'.
Msg 207, Level 16, State 1, Line 21
Invalid column name 'MonthName'.
Msg 207, Level 16, State 1, Line 21
Invalid column name 'MonthName'.
Msg 207, Level 16, State 1, Line 21
Invalid column name 'MonthName'.
Msg 207, Level 16, State 1, Line 21
Invalid column name 'MonthName'.
Msg 104, Level 16, State 1, Line 35
ORDER BY items must appear in the select list if the statement contains a UNION, INTERSECT or EXCEPT operator.

Author

Commented:
ewangoya,

your second query worked great but I have January 2013 appearing at the top. How do I get that to appear on the bottom?

output
Ephraim WangoyaSoftware Engineer

Commented:
My first post had errors, the second one works fine.
Ephraim WangoyaSoftware Engineer
Commented:
Change the order by, start with year

order by
		YearName,
          case MonthName
			when 'January' then 1
			when 'February' then 2
			when 'March' then 3
			when 'April' then 4
			when 'May' then 5
			when 'June' then 6
			when 'July' then 7
			when 'August' then 8
			when 'September' then 9
			when 'October' then 10
			when 'November' then 11
			when 'December' then 12
			else 13
		end

Open in new window

Author

Commented:
that worked great! thank you

Author

Commented:
Great
Scott PletcherSenior DBA
Most Valuable Expert 2018
Top Expert 2014

Commented:
So I guess you never tried my query?

Author

Commented:
sorry Scott, I didn't. I was going through the solutions in the order they were posted. But thanks to you and everyone else who posted. I just went with the first working solution
Top Expert 2012

Commented:
I was going through the solutions in the order they were posted.
Then I guess you overlooked my comment here http:#a38731853:
Try it this way (notice how I also reversed the order of the year and month)

Author

Commented:
Didn't "overlook" it. The solution posted right before your was the first one that worked for me.
Top Expert 2012

Commented:
I was referring to the ORDER BY and your comment today:
your second query worked great but I have January 2013 appearing at the top. How do I get that to appear on the bottom?
I suspect you overlooked my comment:
Try it this way (notice how I also reversed the order of the year and month)

Author

Commented:
No, I missed that and was checking ewangoya's response to my question. Thank you for your posts!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial