GROUP BY Month,在SELECT List中显示月份名称

时间:2016-07-11 15:49:18

标签: tsql group-by sql-server-2014

我正在尝试按月分组将结果集分成月度细分,但我想显示月份名称而不是月份数字。

SELECT  
    DATEPART(MONTH, R.received_date) AS [Month],
    --DATENAME( MONTH, DATEPART( MONTH, R.received_date)) AS [Month] ,
    o.name AS [CountyName] ,
    rsc.description AS [Filing],
    COUNT(*) AS [Total] 
FROM    dbo.requests AS [r]
    INNER JOIN dbo.organizations AS [o] ON o.id = r.submitted_to_organiztion_id
    INNER JOIN dbo.request_status_codes AS [rsc] ON rsc.code = r.request_status_code
WHERE   r.submitted_to_organiztion_id < 68
    AND r.request_type_code = 1
    AND CAST(r.received_date AS DATE) >= '01/01/2016'
    AND CAST(r.received_date AS DATE) <= '06/30/2016'
    AND o.name = 'Alachua'
GROUP BY
    DATEPART(MONTH, R.received_date) ,
    --DATENAME( MONTH, DATEPART( MONTH, R.received_date)) ,
    o.name ,
    rsc.description;

结果预计如下:

GROUP BY Month

但是如果我按DATENAME分组,结果就不是我对下面查询的期望:

SELECT  
    --DATEPART(MONTH, R.received_date) AS [Month],
    DATENAME( MONTH, DATEPART( MONTH, R.received_date)) AS [Month] ,
    o.name AS [CountyName] ,
    rsc.description AS [Filing],
    COUNT(*) AS [Total] 
FROM    dbo.requests AS [r]
    INNER JOIN dbo.organizations AS [o] ON o.id = r.submitted_to_organiztion_id
    INNER JOIN dbo.request_status_codes AS [rsc] ON rsc.code = r.request_status_code
WHERE   r.submitted_to_organiztion_id < 68
    AND r.request_type_code = 1
    AND CAST(r.received_date AS DATE) >= '01/01/2016'
    AND CAST(r.received_date AS DATE) <= '06/30/2016'
    AND o.name = 'Alachua'
GROUP BY
    --DATEPART(MONTH, R.received_date) ,
    DATENAME( MONTH, DATEPART( MONTH, R.received_date)) ,
    o.name ,
    rsc.description
ORDER BY
    [Month] ,
    CountyName ,
    Filing

当6个月组成一组时 - 1月:

Wrong GROUPING

如何修复查询以显示第一个结果集但使用月份名称而不是数值?

谢谢,

0 个答案:

没有答案