Avatar of Samooramad
Samooramad
 asked on

Order by for Month Names

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
Microsoft SQL ServerMicrosoft SQL Server 2005SQL

Avatar of undefined
Last Comment
Samooramad

8/22/2022 - Mon
Steve Wales

Change your

order by MonthName, YearName

to:

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

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

ASKER
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 Wales

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.
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
Imran Javed Zia

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 Wangoya

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

ASKER CERTIFIED SOLUTION
Ephraim Wangoya

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Anthony Perkins

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

⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Samooramad

ASKER
sjwales,

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

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 Pletcher

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])
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
keyu

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
Samooramad

ASKER
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'.
Samooramad

ASKER
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.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Samooramad

ASKER
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 Wangoya

My first post had errors, the second one works fine.
SOLUTION
Ephraim Wangoya

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Samooramad

ASKER
that worked great! thank you
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
Samooramad

ASKER
Great
Scott Pletcher

So I guess you never tried my query?
Samooramad

ASKER
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
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Anthony Perkins

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)
Samooramad

ASKER
Didn't "overlook" it. The solution posted right before your was the first one that worked for me.
Anthony Perkins

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)
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
Samooramad

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