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
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?
SELECT clause This will be the name used to reference this subquery or any of its fields. The trick to placing a subquery in the select clause is that the subquery must return a single value. This is why an aggregate function such as the SUM, COUNT, MIN, or MAX function is commonly used in the subquery.
The AGGREGATE function is designed for columns of data, or vertical ranges. It is not designed for rows of data, or horizontal ranges. For example, when you subtotal a horizontal range using option 1, such as AGGREGATE(1, 1, ref1), hiding a column does not affect the aggregate sum value.
Translated to SQL logic, this is the aggregation of aggregated data, or multi-level aggregation. For aggregation purposes, there are the SQL aggregate functions. And for multi-level aggregation, you'd use (at least) two aggregate functions at the same time.
An aggregate function in SQL performs a calculation on multiple values and returns a single value. SQL provides many aggregate functions that include avg, count, sum, min, max, etc. An aggregate function ignores NULL values when it performs the calculation, except for the count function.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With