DATENAME未与Group By

时间:2017-07-05 13:00:29

标签: sql

我有一个SQL查询,可以按预期返回数据:

 SELECT intMonth as Month
, intYear AS Year,
Sum([intExposureHours]) as [Total Hours]
  FROM tblSSQReleaseToMajor RTM 
  INNER JOIN tblCompany C On RTM.CompanyID = C.CompanyID
    AND C.bitActive = 1 
  INNER JOIN [tblIncidentDetailByOperatorByMonth] BM ON RTM.MajorID = BM.OperatorID
    AND BM.ContractorID = RTM.CompanyID 
        AND BM.OperatorID = 47792
    AND BM.intYear = 2017
        Group By intMonth, intYear

enter image description here

但是,当我尝试将数字月份更改为月份名称时,如下所示:

SELECT DateName(month,intMonth) as Month
, intYear AS Year,
Sum([intExposureHours]) as [Total Hours]
  FROM tblSSQReleaseToMajor RTM 
  INNER JOIN tblCompany C On RTM.CompanyID = C.CompanyID
    AND C.bitActive = 1 
  INNER JOIN [tblIncidentDetailByOperatorByMonth] BM ON RTM.MajorID = BM.OperatorID
    AND BM.ContractorID = RTM.CompanyID 
        AND BM.OperatorID = 47792
    AND BM.intYear = 2017
        Group By intMonth, intYear

我明白了:

enter image description here

更改" Group By"条款为" Group By DateName(month,intMonth), intYear"

产生这个:

enter image description here

有谁能告诉我为什么我没有得到一月,二月,三月,四月五月?

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

DATENAME仅适用于实际日期。你必须做一些hacky才能让它发挥作用。

SELECT DATENAME(month, DATEADD(month, intMonth - 1, CAST('2017-01-01' AS DATETIME))) as Month
, intYear AS Year,
Sum([intExposureHours]) as [Total Hours]
  FROM tblSSQReleaseToMajor RTM 
  INNER JOIN tblCompany C On RTM.CompanyID = C.CompanyID
    AND C.bitActive = 1 
  INNER JOIN [tblIncidentDetailByOperatorByMonth] BM ON RTM.MajorID = BM.OperatorID
    AND BM.ContractorID = RTM.CompanyID 
        AND BM.OperatorID = 47792
    AND BM.intYear = 2017
        Group By intMonth, intYear

编辑:抱歉,要回答您为何会出现这种情况的问题,请尝试以下问题:

SELECT CAST(1 AS DATETIME) -- 1900-01-02 00:00:00.000
SELECT CAST(42919 AS DATETIME) -- is today, the 42,919th day since January 1, 1900

SQL Server实际上将日期存储为整数。当您将“1”作为日期时,它会将其视为“1900-01-02 00:00:00.000”。因此,它表示所有结果的月份是1月份,因为您输入的数字为1-12。它认为你说的是​​1900年1月2日至13日。这就是为什么它为每个人抓一月份的原因。