0

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

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
4

2 回答 2

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()

于 2013-01-24T19:22:22.653 回答
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
于 2013-01-24T19:31:38.360 回答