【问题标题】:SQL Cannot perform an aggregate function on an expression containing an aggregate or a subquerySQL 无法对包含聚合或子查询的表达式执行聚合函数
【发布时间】:2012-10-14 03:26:34
【问题描述】:

我是 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)

但是做这个检查很重要;我该如何解决这个问题?

【问题讨论】:

    标签: sql select sql-server-2008-r2 case


    【解决方案1】:

    您可以将聚合移出一级。
    虽然可以根据您的情况重写查询,但我认为最好以这种方式表达它,以便您可以轻松理解和重用该模式。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多