SQL查询月份名称排序

问题描述 投票:0回答:4

我正在尝试转换此SQL视图以按顺序对月份名称进行排序。任何帮助,将不胜感激:

SELECT    DATENAME(Month, REQDATE) AS Month, COUNT(WO_NUM) AS Tickets
FROM      dbo.TASKS
WHERE     (REQDATE >= '6/1/13')
GROUP BY  DATENAME(Month, REQDATE)

它目前显示无序的月份..

sql sql-server
4个回答
0
投票

试试这个。

SELECT    MAX(DATENAME(Month, REQDATE)) AS Month, COUNT(WO_NUM) AS Tickets
FROM      dbo.TASKS
WHERE     (REQDATE >= '6/1/13')
GROUP BY  DATEPART(Month, REQDATE)  
ORDER BY  DATEPART(Month, REQDATE) ASC

SQL小提琴:http://sqlfiddle.com/#!3/220be/4


4
投票

这将显示按日历顺序列出的月份的结果。

SELECT    DATENAME(Month, REQDATE) AS Month, COUNT(WO_NUM) AS Tickets
FROM      dbo.TASKS
WHERE     (REQDATE >= '6/1/13')
GROUP BY  DATENAME(Month, REQDATE), DATEPART(Month, REQDATE)
ORDER BY  DATEPART(Month, REQDATE) ASC

我将DATEPART(Month, REQDATE)添加到GROUP BY子句中,该子句不应影响分组,因为DATEPART函数的结果对于每个组中的所有日期都是相同的。


0
投票

TSQL函数DatePart()应该以月为整数。试试这个:

SELECT    DATENAME(Month, REQDATE) AS Month, COUNT(WO_NUM) AS Tickets
FROM      dbo.TASKS
WHERE     (REQDATE >= '6/1/13')
ORDER BY DatePart(month, REQDATE)
GROUP BY  DatePart(Month, REQDATE), DateName(Month, REQDATE)

0
投票

如果有人还在寻找答案。诀窍是在日期月份使用AVG。

SELECT    DATENAME(Month, REQDATE) AS Month, COUNT(WO_NUM) AS Tickets, AVG(DATEPART(mm, REQDATE)) AS MonthNum
FROM      dbo.TASKS
WHERE     (REQDATE >= '6/1/13')
GROUP BY  DATENAME(Month, REQDATE)  
ORDER BY  MonthNum ASC
© www.soinside.com 2019 - 2024. All rights reserved.