简体   繁体   English

MySQL查询-使用CAST和SUM时无效使用组函数

[英]MySQL Query - Invalid use of group function when using CAST and SUM

I have the following query that's generating the "Invalid use of group function" error: 我有以下查询正在生成“无效使用组函数”错误:

SELECT dac_name, unit_name, ptn, unit_type, monthly_recurring, directory_charges
FROM sprint WHERE date='$current_sprint_date' AND CAST( directory_charges AS DECIMAL( 10, 2 ) ) > SUM( CAST( directory_charges AS DECIMAL( 10, 2 ) ) * .01) ORDER BY CAST(directory_charges AS DECIMAL(10,2)) DESC LIMIT 10; 

Can't seem to figure it out. 似乎无法弄清楚。 Any help is greatly appreciated. 任何帮助是极大的赞赏。

You can't use an aggregate function like SUM() in a WHERE clause. 您不能在WHERE子句中使用SUM()类的聚合函数。 Aggregates are dependent on the rows that are selected, so using them while selecting rows doesn't make sense. 聚合取决于所选的行,因此在选择行时使用它们没有意义。 You can use it in a HAVING clause, which performs a second filter after rows have been selected and processed: 您可以在HAVING子句中使用它,该子句在选择和处理行之后执行第二个过滤器:

SELECT dac_name, unit_name, ptn, unit_type, monthly_recurring, directory_charges
FROM sprint
WHERE date='$current_sprint_date'
HAVING CAST( directory_charges AS DECIMAL( 10, 2 ) ) > SUM( CAST( directory_charges AS DECIMAL( 10, 2 ) ) * .01)
ORDER BY CAST(directory_charges AS DECIMAL(10,2)) DESC
LIMIT 10;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM