案例表达式中的聚合函数错误

时间:2019-12-18 18:21:19

标签: sql teradata

我有这个查询

SELECT mylearning.Employee_Id,
 case 
        when max(case when not mylearning.CourseStatusTXT = 'Completed' then 1 else 0 end) = 0 then '2018 Complete'
        when max(case when mylearning.CourseStatusTXT in ('Started', 'Not Started') then 1 else 0 end) = 1 then '2018 Not Complete'
  end as Completion_Status
FROM  Analytics.myLearning_Completions as mylearning inner join Analytics.Workday WD on mylearning.Employee_ID = WD.Employee_ID

我想在第一个when语句中添加一个条件,使它像这样

 when max(case when not mylearning.CourseStatusTXT = 'Completed' then 1 else 0 end) = 0 
             and WD.Adjusted_Hire_Date like '2019% '
            and mylearning.CourseTimeCompletedH < cast (WD.Adjusted_Hire_Date as date format 'YYYY/MM/DD') +7
             then '2018 Complete'

但我不断收到此错误

Executed as Single statement.  Failed [3504 : HY000] Selected non-aggregate values must be part of the associated group. 
Elapsed time = 00:00:00.069 

我该如何解决?

3 个答案:

答案 0 :(得分:1)

就像其他提到的那样,您正在尝试在计算中将分组数据与非聚合数据混合在一起,这就是为什么会出现3504错误的原因。您需要将引用的列包括在GROUP BY中,或者将它们包含在汇总函数(即MAX)中。

我不确定这是否是您要追求的目标,但希望它能对您有所帮助。

SELECT 
  mylearning.Employee_Id,
  CASE
    WHEN 
      MAX(CASE WHEN NOT mylearning.CourseStatusTXT = 'Completed' THEN 1 ELSE 0 END) = 0 AND
      WD.Adjusted_Hire_Date like '2019% ' AND
      -- Check if most recently completed course is before Hire (Date + 1 week)
      MAX(mylearning.CourseTimeCompletedH) < 
      CAST(WD.Adjusted_Hire_Date AS DATE FORMAT 'YYYY/MM/DD') + 7 
    THEN '2018 Complete' -- No incomplete learnings
    WHEN MAX(
      CASE WHEN mylearning.CourseStatusTXT IN ('Started', 'Not Started') THEN 1 ELSE 0 END
    ) = 1 THEN '2018 Not Complete' -- Started / Not Started learnings exist
  END AS Completion_Status
FROM Analytics.myLearning_Completions as mylearning  -- Get learning info
INNER JOIN Analytics.Workday WD on mylearning.Employee_ID = WD.Employee_ID -- Employee info
GROUP BY mylearning.Employee_Id, WD.Adjusted_Hire_Date

这将为您提供每个员工的摘要,并有以下两个假设:

  1. 假设employee_ID中的Analytics.Workday值是唯一值(一对一联接),要在比较中使用WD.Adjusted_Hire_Date,只需将其包括在GROUP BY

  2. 假设每个employee_Id有多门课程,为了在比较中使用mylearning.CourseTimeCompletedH,您需要将其包装成MAX之类的集合。

这里需要说明的是,查询将检查每个员工最近完成的课程是否在“ hire_date”表达式之前,所以我不确定这是否是您要的。

尝试一下,让我知道。

答案 1 :(得分:0)

这里的问题是,您在同一查询中将详细信息逐行混合到组或聚合数据中。除非您具有group by子句,否则汇总数据将为所有行输出一个值。如果您有一个group by子句,则它将为每个组输出一个值。分组时,您还可以包括group by子句中的任何值,因为它们对于组是唯一的。

如果要为每个员工提供此数据,则可以按employee_id分组。其他任何数据也需要像Max(Adjusted_Hire_Date)

这样的汇总。

答案 2 :(得分:0)

也许这就是您想要的?

SELECT 
  mylearning.employee_id
  , case 
    when CourseStatusTXT = 'Completed' and WD.Adjusted_Hire_Date like '2019%' 
      and mylearning.CourseTimeCompletedH < cast (WD.Adjusted_Hire_Date as date format 'YYYY/MM/DD') +7
    then '2018 Complete'
    else '2018 Not Complete'
  end CompletionStatus
FROM  myLearning_Completions mylearning, Workday WD 
WHERE mylearning.employee_id = WD.employee_id