I have a query like this
我有这样的查询
SELECT Id
,sum(CASE
WHEN ErrorId NOT IN (
,10
,11
,12
,13
)
THEN 1
ELSE 0
END) errorCount
FROM Table
group by Id
I don't like the hardcoded list of ids and I have a simple query that will get me what I want
我不喜欢硬编码的ID列表,我有一个简单的查询,可以得到我想要的东西
SELECT Id
,sum(CASE
WHEN ErrorId NOT IN (
select ErrorId from Errors where ErrorCategory = 'Ignore_Error'
)
THEN 1
ELSE 0
END) errorCount
FROM Table
group by Id
However when I try this I get
但是,当我尝试这个时,我得到了
Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
无法对包含聚合或子查询的表达式执行聚合函数。
What is my best way ahead?
我未来的最佳方式是什么?
1 个解决方案
#1
3
As stated in error message you cannot use Aggregate
function on top of Sub-Query
如错误消息中所述,您不能在子查询之上使用聚合函数
Here is the correct way to do it
这是正确的方法
SELECT t.Id,
Count(e.ErrorId) errorCount
FROM Table t
LEFT JOIN Errors e
ON t.ErrorId = e.ErrorId
AND e.ErrorCategory = 'Ignore_Error'
GROUP BY t.Id
Another way will be using Outer Apply
另一种方法是使用外部应用
SELECT t.Id,
Count(ou.ErrorId) errorCount
FROM Table t
OUTER apply (SELECT e.ErrorId
FROM Errors e
WHERE t.ErrorId = e.ErrorId
AND e.ErrorCategory = 'Ignore_Error') ou
GROUP BY t.id
#1
3
As stated in error message you cannot use Aggregate
function on top of Sub-Query
如错误消息中所述,您不能在子查询之上使用聚合函数
Here is the correct way to do it
这是正确的方法
SELECT t.Id,
Count(e.ErrorId) errorCount
FROM Table t
LEFT JOIN Errors e
ON t.ErrorId = e.ErrorId
AND e.ErrorCategory = 'Ignore_Error'
GROUP BY t.Id
Another way will be using Outer Apply
另一种方法是使用外部应用
SELECT t.Id,
Count(ou.ErrorId) errorCount
FROM Table t
OUTER apply (SELECT e.ErrorId
FROM Errors e
WHERE t.ErrorId = e.ErrorId
AND e.ErrorCategory = 'Ignore_Error') ou
GROUP BY t.id