Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Sql Query by Month

I am having a sql query as :

select dateName(month, DateAccessed) "Month"
, count(1) totalVisits
, count(distinct l.userName) UsersVisit
from and where clause goes here
group by dateName(monthDateAccessed)
order by Month

The output I get is

Month   totalVisits   UsersVisit
April         100       25
February      200       35
July          300       45
March         400       55
May           500       65

But the ouput I want is in the order of:

February      200       35
March         400       55
April         100       25
May           500       65
July          300       45

How can I get this ?

like image 422
hello temp11 Avatar asked Nov 18 '25 08:11

hello temp11


1 Answers

Use either month(DateAccessed) or datepart(month, DateAccessed) to extract the month number and use that in the order by clause. You will however have to add it to the group by clause too:

SELECT 
    DATENAME(month, DateAccessed) "Month", 
    COUNT(1) totalVisits, 
    COUNT(DISTINCT l.userName) UsersVisit 
FROM and where clause goes here
GROUP BY 
    MONTH(dateaccessed), 
    DATENAME(month, DateAccessed)
ORDER BY 
    MONTH(dateaccessed);

If your data holds data for more than one year you should include the year in the group- and order by clauses (and select statement) if you don't already make sure you only get data from one year in the where clause.

like image 101
jpw Avatar answered Nov 20 '25 11:11

jpw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!