接收'聚合不能出现在ON子句中#39;错误

时间:2017-03-21 14:21:38

标签: sql sql-server-2012

我收到此错误:聚合不能出现在ON子句中,除非它位于HAVING子句或选择列表中包含的子查询中,并且要聚合的列是外部引用。

我不知道如何解决这个问题,请帮助。

set datefirst 2

select [Table 2].[Active_Headcount]
    , DATEADD(DD, 7 - (DATEPART(DW, MIN([Table 1].[Term Date]))), MIN([Table 1].[Term Date])) as EndOfWeek
    , COUNT(*) as TermsPerWeek
from [Table 1]
left join [Table 2]
    on (DATEADD(DD, 7 - (DATEPART(DW, MIN([Table 1].[Term Date]))), MIN([Table 1].[Term Date]))) = [Table 2].[WeekDate]
where [Table 1].[Term Date] not like 'null'
    and (
        [Table 1].[Term Date] like '%2016%'
        or [Table 1].[Term Date] like '%2017%'
        )
group by DATEPART(WEEK, [Table 1].[Term Date])
    , [Table 2].[Active_Headcount]
order by EndOfWeek asc;

2 个答案:

答案 0 :(得分:0)

基本上就是它所说的。您无法在ON条件的JOIN子句中执行聚合操作。您需要使用APPLY运算符。

此外,我将从您的代码中假设[HeadcountByWeek]是您的"table 2"

set datefirst 2

select Active_Headcount
    , DATEADD(DD, 7 - (DATEPART(DW, MIN([Term Date]))), MIN([Term Date])) as EndOfWeek
    , COUNT(*) as TermsPerWeek
from table t1
outer apply (
    select * 
    from [HeadcountByWeek] t2 
    where (DATEADD(DD, 7 - (DATEPART(DW, MIN(t1.[Term Date]))), MIN(t1.[Term Date]))) = t2.[WeekDate] ) t2
where t1.[Term Date] not like 'null'
    and (
        t1.[Term Date] like '%2016%'
        or t1.[Term Date] like '%2017%'
        )
group by DATEPART(WEEK, t1.[Term Date])
    , t1.[Active_Headcount]
order by EndOfWeek asc;

答案 1 :(得分:0)

我会做这样的事情:

set datefirst 2;

With cte(Active_Headcount, EndOfWeek, TermsPerWeek)
as (select Active_Headcount
, DATEADD(DD, 7 - (DATEPART(DW, MIN([Term Date]))), MIN([Term Date])) as EndOfWeek
, COUNT(*) as TermsPerWeek
from table 1
)
select * from cte
left join table 2
on cte.EndOfWeek = [HeadcountByWeek].[WeekDate]
where [Term Date] not like 'null'
and (
    [Term Date] like '%2016%'
    or [Term Date] like '%2017%'
    )
 group by DATEPART(WEEK, [Term Date])
, [Active_Headcount]
order by EndOfWeek asc;

这不会开箱即用,因为我不知道哪些列来自哪个表。

主要思想是将查询分解为CTE,然后在下面的联接中使用该cte中的列。