我一直在寻找这个看似简单的问题的解决方案。只有当我在 where 子句中引入最后一个 sum() 函数时,查询才会中断。我收到错误“错误代码:1111。组函数使用无效。”我不明白为什么它不允许我做这个 where 语句。
查询
select
dIntervalStart,
weekofyear(dIntervalStart) WeekOfYear,
weekday(dIntervalStart) DayOfWeek,
cast(dIntervalStart as time) IntervalStart,
sum(nExternToInternAcdCalls) CallVolume
from
iwrkgrpqueuestats
where
SiteId = 1
and cname in ('applications' , 'employer',
'factfind',
'general',
'other')
and cReportGroup = '*'
and CAST(dIntervalStart as time) between '07:00' and '17:30'
and weekday(dIntervalStart) not in (5 , 6)
and sum(nExternToInternAcdCalls) <> 0
group by weekofyear(dIntervalStart) , weekday(dIntervalStart) , cast(dIntervalStart as time)
order by IntervalStart asc, dIntervalStart desc
最佳答案
将聚合表达式上的谓词重新定位到 HAVING
子句,例如:
GROUP BY ...
HAVING sum(nExternToInternAcdCalls) <> 0
ORDER BY ...
WHERE 子句中的谓词在访问行时进行评估,它们挑选出包含哪些行。访问行时,聚合表达式的值(例如 SUM(foo)
)不可用。直到访问行之后才能确定该表达式的值。
HAVING
子句中的谓词在访问行之后和准备结果集之后应用。当评估 HAVING 谓词时,聚合 (SUM(foo)
) 将可用。
注意:GROUP BY
子句通常会包括 SELECT 列表中的所有非聚合表达式。 MySQL 比其他数据库更宽松,这既是福也是祸;如果 GROUP BY“折叠”行,对于 SELECT 列表中的非聚合,MySQL 返回来自一个行的值。
也就是说,如果你 GROUP BY weekofyear(foo)
,并在 SELECT 列表中返回 foo
,并且有多个 foo 值的行计算结果相同weekofyear(foo)
值,MySQL 将为给定的 weekofyear(foo)
返回一行,并返回 一个 的 foo 值>行中的一个。其他数据库(Oracle、SQL Server 等)会抛出错误而不是返回结果集。
关于mysql - 群组功能使用无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23203179/