2012-10-14 4 views
2

집계 또는 하위 쿼리가 포함 된 식에서는 집계 함수를 수행 할 수 없습니다와 나는 다음과 같은 SQL 쿼리를SQL 내가 SQL에 새로운 오전

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 

을했습니다 그것은 나에게 다음과 같은 오류를 제공

Cannot perform an aggregate function on an expression containing an aggregat or a subquery 
나는 다음 줄을 제거하면

은 그것을 잘

AND NOT EXISTS (select CAST(booked AS INT) FROM bookedordersids b where b.booked = o.orderid) 

작동하지만이 체을하는 것이 중요합니다 ck; 이 문제를 어떻게 해결할 수 있습니까?

답변

2

집계를 한 수준 아래로 이동할 수 있습니다.
사례에서 검색어를 다시 작성할 수 있지만이 방식으로 표현하는 것이 가장 좋다고 생각하므로 패턴을 쉽게 이해하고 재사용 할 수 있습니다.

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 
관련 문제