无法对包含聚合或子查询但需要筛选结果的表达式执行聚合函数

时间:2017-05-26 20:43:54

标签: sql subquery aggregate

我收到了以下代码的错误消息

在嵌套查询中

FROM(
    SELECT  SUM(CASE (select TotalBasePayAnnualizedAmt from WDHRISedw.edaHR.WorkerPosition where WDHRISedw.edaHR.WorkerPosition.EmployeeID = Employee_ID) 
                WHEN NULL THEN 0 
                WHEN 0 THEN 0 
                ELSE GrossPay / (select TotalBasePayAnnualizedAmt from WDHRISedw.edaHR.WorkerPosition where WDHRISedw.edaHR.WorkerPosition.EmployeeID = Employee_ID) * 200 
            END
            ) AS [Paid FTE],
        Employee_ID, 
        Position_ID, EarnedPeriodEndDate
        FROM
        WDHRISods.WD.ActualDistributions

如何修改以避免错误?

2 个答案:

答案 0 :(得分:0)

这是生成错误的查询:

     SELECT SUM(CASE (select TotalBasePayAnnualizedAmt from WDHRISedw.edaHR.WorkerPosition where WDHRISedw.edaHR.WorkerPosition.EmployeeID = Employee_ID) 
                    WHEN NULL THEN 0 
                    WHEN 0 THEN 0 
                    ELSE GrossPay / (select TotalBasePayAnnualizedAmt from WDHRISedw.edaHR.WorkerPosition where WDHRISedw.edaHR.WorkerPosition.EmployeeID = Employee_ID) * 200 
                 END
                ) AS [Paid FTE],
          Employee_ID, Position_ID, EarnedPeriodEndDate
    FROM WDHRISods.WD.ActualDistributions

将其替换为JOIN和聚合:

    SELECT COALESCE(ad.GrossPay * 200 / NULLIF(wp.TotalBasePayAnnualizedAmt, 0), 0) as [Paid FTE],
          ad.Employee_ID, ad.Position_ID, ad.EarnedPeriodEndDate
    FROM WDHRISods.WD.ActualDistributions ad LEFT JOIN
         (SELECT wp.EmployeeId, SUM(TotalBasePayAnnualizedAmt) as TotalBasePayAnnualizedAmt
          FROM WDHRISedw.edaHR.WorkerPosition wp
          GROUP BY wp.Employee_ID
         ) wp
         ON wp.EmployeeID = ad.Employee_ID

答案 1 :(得分:0)

我有来自WDHRISedw.edaHR.WorkerPosition的表中的TotalBasePayAnnualizedAmt具有相同的EID并完成全时费率计算