2012-10-14 52 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 
相關問題