简体   繁体   中英

In Sql Server 2008 Order by clause is not working

I have run a query

SELECT Datename(MM, CONVERT(DATE, created_date))           AS open_date, 
       Count(Datename(MONTH, CONVERT(DATE, created_date))) AS created_request 
FROM   usm_request 
WHERE  Datename(YEAR, CONVERT(DATE, created_date)) = Datename(YEAR, Getdate()) 
GROUP  BY Datename(MM, CONVERT(DATE, created_date)) 
ORDER  BY Datename(MM, CONVERT(DATE, created_date)) ASC 

and got the result

 open_date  created_request

   April          4
   February      194
   January       540
   March         186

But we need result as

  open_date  created_request

   January       540
   February      194
   March         186    
   April          4

Please help me.

Regards

Pankaj

DATENAME returns a string not a datetime, so you get a lexicographic ordering.

You could use:

SELECT Datename(MM, CONVERT(DATE, created_date))           AS open_date, 
       Count(Datename(MONTH, CONVERT(DATE, created_date))) AS created_request 
FROM   usm_request 
WHERE  Datename(YEAR, CONVERT(DATE, created_date)) = Datename(YEAR, Getdate()) 
GROUP  BY  DATENAME(mm,created_date),
       DATEPART(yy, created_date), 
       DATEPART(mm, created_date)
ORDER  BY DATEPART(yy, created_date),
          DATEPART(mm, created_date)

... which orders by year + month (as int ). You also have to include them in the GROUP BY .

However, why do you convert the datetime column always to Date ? That seems to be redundant with methods like DATENAME . So i've omitted it in the GROUP BY and ORDER BY .

Your ORDER BY clause is receiving a string: the name of the month. This is why the rows are ordered alphabetically.

Try ordering by the actual date representation:

ORDER BY CONVERT(DATE, created_date) ASC

SELECT * FROM(
SELECT Datename(MM, CONVERT(DATE, created_date))           AS open_date, 
       Count(Datename(MONTH, CONVERT(DATE, created_date))) AS created_request 
FROM   usm_request 
WHERE  Datename(YEAR, CONVERT(DATE, created_date)) = Datename(YEAR, Getdate()) 
GROUP  BY Datename(MM, CONVERT(DATE, created_date)) 
) a
ORDER  BY a.created_request desc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM