user1570048
user1570048

Reputation: 880

SQL Cannot perform an aggregate function on an expression containing an aggregate or a subquery

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?

Upvotes: 2

Views: 10209

Answers (1)

RichardTheKiwi
RichardTheKiwi

Reputation: 107716

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.

select catalogid, sum(numitems) numitems, sum(allitems) - sum(numitems) ignoreditems
 from (
  select i.catalogid,
    case when (ocardtype in ('PayPal','Sofort') OR
                   ocardtype in ('mastercard','visa') and
                   odate is not null) AND NOT EXISTS (
      select *
      FROM bookedordersids b
      where b.booked = o.orderid)
                   then numitems
                   else 0 end
    numitems,
    numitems allitems
  from orders o
  join oitems i on i.orderid=o.orderid
 ) X
group by catalogid

Upvotes: 2

Related Questions