分组不按预期分组?

时间:2017-08-18 12:04:13

标签: sql-server

我尝试使用此查询计算每月总和。

SELECT
     fld_year
    , fld_month
    , CONVERT(nvarchar(7), fld_ConsDate, 121) AS fld_ConsDate
    , fld_ConsumptionValue
    , fld_Id
FROM (
    SELECT
         YEAR(DATEADD(MINUTE, fld_TZAM - 6360, fld_ConsDateTime)) AS fld_year
        , MONTH(DATEADD(MINUTE, fld_TZAM- 6360, fld_ConsDateTime)) AS fld_month
        , DATEADD(MONTH, DATEDIFF(MONTH, 0, fld_ConsDateTime), 0) AS fld_ConsDate
        , SUM(fld_EnergyTotalIndexValue) AS fld_ConsumptionValue
        , MAX(fld_Id) AS fld_Id
    FROM tbl_EM_DeviceEnergyHourlyConsumption
    WHERE fld_Deleted = 0
        AND fld_Active = 1
        AND fld_CalculationState = 2
        AND fld_DeviceId IN (18)
        AND fld_ConsDateTime >= DATEADD(MINUTE, -1*(fld_TZAM) + 6360, '2017-05-01 00:00:00')
        AND fld_ConsDateTime < DATEADD(MINUTE, -1*(fld_TZAM) + 6360, '2017-08-01 00:00:00')
        AND fld_DeviceOrganizationId IN (SELECT Value FROM dbo.fn_OrganizationSubList(2))
    GROUP BY 
        YEAR(DATEADD(MINUTE, fld_TZAM - 6360, fld_ConsDateTime)), 
        MONTH(DATEADD(MINUTE, fld_TZAM - 6360, fld_ConsDateTime)),
        DATEADD(MONTH, DATEDIFF(MONTH, 0, fld_ConsDateTime), 0),
)T ORDER BY fld_ConsDate ASC

我期望的结果是

fld_year   fld_month     fld_ConsDate     fld_ConsumptionValue   fld_Id
 2017          5            2017-05              294.1340           
 2017          6            2017-06              222.7527           
 2017          7            2017-07              318.2111

但我每月得到2个值

fld_year   fld_month     fld_ConsDate     fld_ConsumptionValue   fld_Id
   2017          5            2017-05              260.2158           
   2017          6            2017-06              193.4958           
   2017          5            2017-06              33.9182
   2017          6            2017-07              29.2569           
   2017          7            2017-07              264.8147           
   2017          7            2017-08              53.3964

我似乎无法找到任何有关我的提示?任何人都可以告诉我我的逻辑出错了吗?提前谢谢!

1 个答案:

答案 0 :(得分:2)

如果您每月只需要一行,为什么要包含第三个聚合键?这样的事情似乎就是你想要的:

   SELECT YEAR(DATEADD(MINUTE, fld_TZAM - 6360, fld_ConsDateTime)) AS fld_year,
          MONTH(DATEADD(MINUTE, fld_TZAM - 6360, fld_ConsDateTime)) AS fld_month,
          DATEADD(MONTH, DATEDIFF(MONTH, 0, MIN(fld_ConsDateTime)), 0) AS fld_ConsDate,
          . . .
    GROUP BY YEAR(DATEADD(MINUTE, fld_TZAM - 6360, fld_ConsDateTime)), 
             MONTH(DATEADD(MINUTE, fld_TZAM - 6360, fld_ConsDateTime))