T-sql在Group By中使用AVG with conditional / where

时间:2017-02-13 13:50:20

标签: sql-server average

T-SQL查询:

  SELECT

    RESULT.Year AS 'Year',
    RESULT.Month AS 'Month',
    RESULT.EmployeeNumber,
    RESULT.StartedWorking,
    RESULT.SeperatedWorking,
    (AVG(RESULT.SeperatedWorking / RESULT.EmployeeNumber * 100)) AS ConversionRate

    FROM (

                    SELECT  
                        YEAR(CreatedAt) AS 'Year', 
                        12 AS 'Month',
                        COUNT(*) AS 'EmployeeNumber',
                        COUNT(EmploymentStartDate) AS 'StartedWorking',
                        COUNT(EmploymentEndDate) AS 'SeperatedWorking'

                    FROM Employees 

                    WHERE IsDeleted = 0

                    GROUP BY 
                    YEAR(CreatedAt)

    ) AS RESULT

问题:

我正在尝试将以下公式用于 ConversionRate列

COUNT(EmploymentEndDate) / COUNT(EmploymentStartDate) * 100

我正在尝试下面的查询中选择以获得如下结果

(AVG(RESULT.SeperatedWorking / RESULT.EmployeeNumber * 100)) AS ConversionRate

此查询显示以下错误AS

"Column 'RESULT.Year' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
"

如何通过将AVG用于“ConversionRate”列来获得正确的结果?

2 个答案:

答案 0 :(得分:2)

您还必须在外部查询中添加group by。像:

SELECT

    RESULT.Year AS 'Year',
    RESULT.Month AS 'Month',
    RESULT.EmployeeNumber,
    RESULT.StartedWorking,
    RESULT.SeperatedWorking,
    (AVG(RESULT.SeperatedWorking / RESULT.EmployeeNumber * 100)) AS ConversionRate

    FROM (

                    SELECT  
                        YEAR(CreatedAt) AS 'Year', 
                        12 AS 'Month',
                        COUNT(*) AS 'EmployeeNumber',
                        COUNT(EmploymentStartDate) AS 'StartedWorking',
                        COUNT(EmploymentEndDate) AS 'SeperatedWorking'

                    FROM Employees 

                    WHERE IsDeleted = 0

                    GROUP BY 
                    YEAR(CreatedAt)

    ) AS RESULT

    GROUP BY
        RESULT.Year,
        RESULT.Month ,
        RESULT.EmployeeNumber,
        RESULT.StartedWorking,
        RESULT.SeperatedWorking

答案 1 :(得分:2)

在选择列表中使用聚合函数时,必须在外部查询中使用GROUP BY。