Click here to Skip to main content
15,891,679 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi All,
am facing one problem in order by in sql.
Actually i want to display order by for year and month
My expected output is:

2015_Jan
2015_Feb
2015_Mar
2015_Apr
2015_May
2015_Jun
2015_Jul
2015_Aug
2015_Sep
2015_Oct
2015_Nov
2015_Dec
2016_Jan
--
-- etc

but as per my code am not getting like that,
i got the alphabetical order, which means,
staring from A to Z

below is my code,

SQL
select billdate from test ORDER BY YEAR(billdate),Month(billdate)


please drop me a solution.

with regards,
stellus

What I have tried:

how to sort year and month order by in sql
Posted
Updated 6-Apr-22 2:55am
v2
Comments
CHill60 10-May-16 9:23am    
Is billdate a datetime field?

Based on your sample query
SQL
select billdate from test ORDER BY YEAR(billdate),Month(billdate)

You are going to have to convert the column to a date to get the correct ordering. E.g.
SQL
select billdate 
from test 
ORDER BY DATEPART(MM,SUBSTRING(billdate,1,4) + SUBSTRING(billdate, 6,3) + '01')

This is a truly awful way to go about things - billdate should be a date or datetime column in which case you could do something like
SQL
select cast(DATEPART(YY,billdate) as varchar) + '_' + convert(char(3), datename(month, billdate))
from test 
ORDER BY billdate

Which is also pretty awful.
What you should be doing is
SQL
select billdate from test order by billdate
and doing the formatting of the result in the presentation (UI) layer
 
Share this answer
 
That's because you are storing information badly: you are storing it as a string, which means that the comparison will always be string based: the first different character determines the result of the whole comparison.
It is possible to do it if you extract the year portion as a string, and then month part as a separate string. You can then use a JOIN to a separate table to convert the short month name to a number, and then use the yera and minth values to ORDER BY.
But...it's clumsy, and a poor idea. It's also goign to be slow every time you want to access or use the field.
Instead, change the column to a DATE or DATETIME and then it's trivial:
SQL
SELECT BillDate FROM test 
ORDER BY DATEPART(yy, BillDate), DATEPART(mm, BillDate)
 
Share this answer
 
select billdate from test ORDER BY YEAR(billdate),Month(billdate),day(billdate).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900