在Sql Server 2008中,Order by子句不起作用

时间:2015-04-14 06:46:20

标签: sql sql-server sql-server-2008

我已经运行了查询

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 

得到了结果

 open_date  created_request

   April          4
   February      194
   January       540
   March         186

但我们需要结果

  open_date  created_request

   January       540
   February      194
   March         186    
   April          4

请帮帮我。

此致

的Pankaj

3 个答案:

答案 0 :(得分:2)

DATENAME返回的字符串不是日期时间,因此您可以获得字典顺序。

您可以使用:

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)

...按年份+月份排序(int)。您还必须将它们包含在GROUP BY

但是,为什么要将datetime列始终转换为Date?对于像DATENAME这样的方法来说,这似乎是多余的。所以我在GROUP BYORDER BY

中省略了它

答案 1 :(得分:1)

您的ORDER BY子句正在接收一个字符串:月份的名称。这就是行按字母顺序排序的原因。

尝试按实际日期表示排序:

ORDER BY CONVERT(DATE, created_date) ASC

答案 2 :(得分:-1)

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