[英]SQL Server Cannot perform an aggregate function on an expression containing an aggregate or a subquery
I'm having an issue with my stored procedure. 我的存储过程存在问题。
I am getting error: 我收到错误:
Cannot perform an aggregate function on an expression containing an aggregate or a subquery 无法对包含聚合或子查询的表达式执行聚合函数
Here's the part of my stored procedure where I believe the error occurs: 这是我的存储过程的一部分,我相信错误发生:
SELECT column_1, column_2,
SUM(CASE WHEN column_2 NOT IN (SELECT product FROM table_products) THEN 1
ELSE 0
END) AS Total
FROM my_table
WHERE is_rated = '1'
GROUP BY column_1, column_2
Thank you. 谢谢。
You'll get much better performance generally if you try to avoid correlated subqueries anyway: 如果您尝试避免相关子查询,通常会获得更好的性能:
SELECT
MT.column_1,
MT.column_2,
SUM(CASE WHEN P.product IS NULL THEN 1 ELSE 0 END) AS total
FROM
My_Table MT
LEFT OUTER JOIN Products P ON P.product = MT.column_2
WHERE
MT.is_rated = '1'
GROUP BY
MT.column_1,
MT.column_2
This assumes that there will only ever be at most one match in the Products table (Products, not Table_Products - of course it's a table so don't put that in the name). 这假设Products表中最多只有一个匹配项(产品,而不是Table_Products - 当然它是一个表,所以不要把它放在名称中)。 In other words, this will work if product is the PK (or an AK) of the Products table. 换句话说,如果product是Products表的PK(或AK),这将起作用。
If that's not the case and you might have multiple matches in the Products
table then you can JOIN
to a subquery that uses DISTINCT
on the product
column. 如果情况并非如此,并且您可能在Products
表中有多个匹配项,那么您可以JOIN
到在product
列上使用DISTINCT
的子查询。
SELECT
column_1, column_2,
SUM(
CASE
WHEN table_products.product IS NULL THEN 1
ELSE 0
END
) AS Total
FROM my_table
left join table_products on my_table.column_2 = table_products.product
WHERE is_rated = '1'
GROUP BY column_1, column_2
You can move the SUM()
logic inside the subquery: 您可以在子查询中移动SUM()
逻辑:
SELECT t.column_1, t.column_2,
(SELECT COUNT(*)
FROM table_products p
WHERE t.column_2 <> p.product
) as Total
FROM my_table t
WHERE t.is_rated = '1'
GROUP BY t.column_1, t.column_2 ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.