简体   繁体   English

在SQL查询中排序月份名称

[英]Sort Month Name in SQL Query

My Current Query is : 我目前的查询是:

SELECT FORMAT(Date, 'MMM') as 'Date', FORMAT(Date, 'yyy') as 'Year' 
,COUNT(*) 
as 'Tickets Generated'
FROM [SambaData2].[dbo].[Tickets]
GROUP BY FORMAT(Date, 'MMM'), FORMAT(Date, 'yyy')
ORDER BY Date

It returns the values: 它返回值:

在此输入图像描述

I would like the same query to return sorted month name with Year! 我希望相同的查询返回年份的已排序月份名称!

For greater query efficiency I would avoid the format() approach. 为了提高查询效率,我会避免使用format()方法。

select
       left(datename(month,[Date]),3) [Month]
     , year([Date]) [Year]
     , [Tickets Generated]
from (
        SELECT
               dateadd(month,datediff(month,0,t.[Date]),0) as [Date]
             , COUNT(*) as [Tickets Generated]
        FROM [SambaData2].[dbo].[Tickets] AS t
        GROUP BY dateadd(month,datediff(month,0,t.[Date]),0)
    ) as d
ORDER BY [Date]

The core to this approach is the following: 这种方法的核心如下:

dateadd(month,datediff(month,0,t.[Date]),0)

this has the effect of locating the first day of the relevant year & month, thus leaving a whole date available for the order by clause, but still grouping to the required level. 这具有定位相关年份和月份的第一天的效果,从而为order by子句留下完整的日期,但仍然分组到所需的级别。 Runing the foillowing may help explain 运行foillowing可能有助于解释

select 
  datediff(month,0,getdate()) a
, dateadd(month,datediff(month,0,getdate()),0) b
, left(datename(month,getdate()),3) c
, getdate() d


   a          b        c              d           
 ------- ------------ ----- --------------------- 
  1425    2018-10-01   Oct   2018-10-04 08:08:19     

Here is another option: 这是另一种选择:

SELECT
    FORMAT(Date, 'yyy') AS Year,
    FORMAT(Date, 'MMM') AS Date,
    COUNT(*) AS [Tickets Generated]
FROM [SambaData2].[dbo].[Tickets]
GROUP BY
    FORMAT(Date, 'yyy'),
    FORMAT(Date, 'MMM')
ORDER BY
    TRY_CONVERT(datetime, FORMAT(Date, 'yyy') + '-' + FORMAT(Date, 'MMM'));

I prefer this method over the accepted answer because it is only uses components in the ORDER BY clause which were actually present in the SELECT clause. 我更喜欢这种方法而不是接受的答案,因为它只使用ORDER BY子句中实际存在于SELECT子句中的组件。 Certain RDBMS would complain about an ORDER BY using components not present in SELECT . 某些RDBMS会使用SELECT不存在的组件来抱怨ORDER BY This answer also assumes that your version of SQL Server supports TRY_CONVERT . 此答案还假定您的SQL Server版本支持TRY_CONVERT

Use year(date), month(date) in order by month() function will give you month number so you can order it easily 使用年份(日期),月份(日期)按月()功能将为您提供月份编号,以便您可以轻松订购

SELECT FORMAT(Date, 'MMM') as 'Date', FORMAT(Date, 'yyy') as 'Year',
COUNT(*) 
as 'Tickets Generated'
FROM [SambaData2].[dbo].[Tickets]
GROUP BY FORMAT(Date, 'MMM'), FORMAT(Date, 'yyy'),year(Date),month(Date)
ORDER BY year(Date),month(Date)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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