I’ve the following SQL Query
select catalogid, numitems, allitems - numitems ignoreditems
from (
select i.catalogid,"
sum(case when (ocardtype in ('PayPal','Sofort') OR
ocardtype in ('mastercard','visa') and
odate is not null) AND NOT EXISTS (select CAST(booked AS INT) FROM bookedordersids b where b.booked = o.orderid)
then numitems
else 0 end) numitems,
sum(numitems) allitems
from orders o
join oitems i on i.orderid=o.orderid
group by i.catalogid
) X
and it gives me the following error
Cannot perform an aggregate function on an expression containing an aggregat or a subquery
When I remove the following line it works fine
AND NOT EXISTS (select CAST(booked AS INT) FROM bookedordersids b where b.booked = o.orderid)
but it’s important to do this check; how can I fix this?
You could just move the aggregation one level out.
While the query can be rewritten in your case, I think it best to express it this way so you can easily understand and reuse the pattern.