无法执行聚合功能

时间:2013-01-24 19:16:38

标签: sql-server

当我尝试运行代码时,我收到以下错误:“无法对包含聚合或子查询的表达式执行聚合函数。”

SELECT dbo.COL_TBL_WAGES.MANUAL, dbo.COL_TBL_VCOURSE.TNG_MDA_TYP_CD, 
    dbo.COL_2010_TRN_RESULTS2.TNG_SYS_NR, 
    COUNT(dbo.COL_2010_TRN_RESULTS2.EMP_TNG_STT_DT) AS CountOfEMP_TNG_STT_DT,
    dbo.COL_MASTER_COURSE_LIST.Length, 
    COUNT(
        COUNT(dbo.COL_2010_TRN_RESULTS2.EMP_TNG_STT_DT) * (
            CASE WHEN IsNumeric([COL_TBL_VCOURSE].[LENGTH]) = 1 
            THEN [COL_TBL_VCOURSE].[LENGTH] 
            ELSE 0 
            END
        )
    ) AS Total_Hours
FROM dbo.COL_TBL_WAGES INNER JOIN
    dbo.COL_2010_TRN_RESULTS2 ON dbo.COL_TBL_WAGES.[Job Group Code] =
        dbo.COL_2010_TRN_RESULTS2.JOB_GRP_CD INNER JOIN
    dbo.COL_MASTER_COURSE_LIST ON dbo.COL_2010_TRN_RESULTS2.TNG_SYS_NR = 
        dbo.COL_MASTER_COURSE_LIST.[GEMS Code] INNER JOIN
    dbo.COL_TBL_VCOURSE ON dbo.COL_2010_TRN_RESULTS2.TNG_SYS_NR = 
        dbo.COL_TBL_VCOURSE.TNG_SYS_NR
GROUP BY dbo.COL_MASTER_COURSE_LIST.Length, dbo.COL_TBL_WAGES.MANUAL,
    dbo.COL_TBL_VCOURSE.TNG_MDA_TYP_CD, 
    dbo.COL_2010_TRN_RESULTS2.TNG_SYS_NR

2 个答案:

答案 0 :(得分:2)

您无法嵌套这样的聚合函数。您必须使用子查询来获得结果:

select MANUAL,
  TNG_MDA_TYP_CD,
  TNG_SYS_NR,
  CountOfEMP_TNG_STT_DT,
  Length,
  count(Total_Hours) Total_Hours,
from
(
  SELECT dbo.COL_TBL_WAGES.MANUAL, 
    dbo.COL_TBL_VCOURSE.TNG_MDA_TYP_CD, 
    dbo.COL_2010_TRN_RESULTS2.TNG_SYS_NR, 
    COUNT(dbo.COL_2010_TRN_RESULTS2.EMP_TNG_STT_DT) AS CountOfEMP_TNG_STT_DT, 
    dbo.COL_MASTER_COURSE_LIST.Length, 
    COUNT(dbo.COL_2010_TRN_RESULTS2.EMP_TNG_STT_DT) 
            * (CASE WHEN IsNumeric([COL_TBL_VCOURSE].[LENGTH]) = 1 
               THEN [COL_TBL_VCOURSE].[LENGTH] 
               ELSE 0 END) AS Total_Hours
  FROM dbo.COL_TBL_WAGES 
  INNER JOIN dbo.COL_2010_TRN_RESULTS2 
    ON dbo.COL_TBL_WAGES.[Job Group Code] = dbo.COL_2010_TRN_RESULTS2.JOB_GRP_CD 
  INNER JOIN dbo.COL_MASTER_COURSE_LIST 
    ON dbo.COL_2010_TRN_RESULTS2.TNG_SYS_NR = dbo.COL_MASTER_COURSE_LIST.[GEMS Code] 
  INNER JOIN dbo.COL_TBL_VCOURSE 
    ON dbo.COL_2010_TRN_RESULTS2.TNG_SYS_NR = dbo.COL_TBL_VCOURSE.TNG_SYS_NR
  GROUP BY dbo.COL_MASTER_COURSE_LIST.Length, 
    dbo.COL_TBL_WAGES.MANUAL, 
    dbo.COL_TBL_VCOURSE.TNG_MDA_TYP_CD, 
    dbo.COL_2010_TRN_RESULTS2.TNG_SYS_NR
) src
group by MANUAL,
  TNG_MDA_TYP_CD,
  TNG_SYS_NR,
  CountOfEMP_TNG_STT_DT,
  Length

在不知道您对查询的意图的情况下,您可能需要将count()替换为sum()

答案 1 :(得分:0)

听起来好像你在混淆COUNT()和SUM()。 COUNT只计算所有非NULL值。 SUM添加您提供的任何数值。

例如,如果您在以下值上执行COUNT和SUM,则会得到以下结果。

VAL
100
50
25
0

SUM(VAL) = 175
COUNT(VAL) = 4

这就是我认为你真正想要的:

SUM(
        CASE WHEN IsNumeric([COL_TBL_VCOURSE].[LENGTH]) = 1 
        THEN 1
        ELSE 0 
        END
    ) AS Total_Hours