GROUP BY和ORDER BY日期为月

时间:2016-07-31 18:51:37

标签: sql sql-server tsql

我的数据以日期时间格式存储,即2016-01-20 03:00:11.000

我的目标是以月(字符串)格式显示数据并按月显示。

我想得到什么(按月份排序) -

+----------+-------+
|  Month   | Count |
+----------+-------+
| January  |    87 |
| February |    64 |
| March    |    48 |
| April    |    67 |
| May      |    49 |
+----------+-------+
... rest of months

我得到了什么(按字母排序而不是几个月) -

+-----------+-------+
|   Month   | Count |
+-----------+-------+
| April     |    87 |
| August    |    64 |
| December  |    48 |
| February  |    67 |
| January   |    49 |
| July      |    41 |
| June      |    44 |
| March     |    71 |
| May       |    62 |
| November  |    51 |
| October   |    44 |
| September |    48 |
+-----------+-------+

我的尝试 -

  SELECT  DATENAME(MONTH,[mydate]) as Month, count([ID]) AS Count
  FROM [dbo].[mytable]
  group by DATENAME(MONTH,[mydate])

尝试订购(不工作) -

SELECT  DATENAME(MONTH,[mydate]) as Month, count([mydate]) AS Count
  FROM [dbo].[mytable]
  group by DATENAME(MONTH,[mydate])
  ORDER BY MONTH([mydate])

由于聚合功能使用不当而导致出现此错误

  

它不包含在聚合函数或GROUP BY子句中。

我不确定如何在这种情况下继续进行。任何帮助表示赞赏。

4 个答案:

答案 0 :(得分:5)

您还需要按月份分组:

IOException

注意:不要把你的计数称为Count,因为这是一个保留字。使用DateCount或其他。

答案 1 :(得分:1)

如果你有一年的数据,那么你可以这样做:

SELECT  DATENAME(MONTH, [mydate]) as Month, count([ID]) AS Count
FROM [dbo].[mytable]
GROUP BY DATENAME(MONTH, [mydate])
ORDER BY MIN(mydate);

注意:效果如何,取决于您的数据。 Trincot的答案更具体到按月号排序。这是按数据排序的。

答案 2 :(得分:0)

ORDER BY
CASE DATENAME(MONTH,[mydate])
    WHEN 'January' THEN 0
    WHEN 'February' THEN 1
    WHEN 'March' THEN 2
    WHEN 'April' THEN 3
    WHEN 'May' THEN 4
    WHEN 'June' THEN 5
    WHEN 'July' THEN 6
    WHEN 'August' THEN 7
    WHEN 'September' THEN 8
    WHEN 'October' THEN 9
    WHEN 'November' THEN 10
    ELSE 11
END

答案 3 :(得分:0)

执行此操作的一种方法是使用窗口函数和子查询,如下所示:

select Month, Count
from
(
    SELECT ROW_NUMBER() OVER (order by MONTH([mydate])) as MonthNumber
    , DATENAME(MONTH,[mydate])
    , count([mydate]) AS Count
      FROM [dbo].[mytable]
      group by DATENAME(MONTH,[mydate])
) results
ORDER BY results.MonthNumber