SQL在选择的情况下使用条件求和

时间:2012-10-20 01:13:35

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

具有以下sql查询

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 AS numitems
      , numitems AS allitems
   from orders AS o
   join oitems AS i on i.orderid = o.orderid
) AS X
group by catalogid

现在我在这里有两张桌子 订单和oitems表

查询根据您看到的条件对numitemsignoreditems进行求和,现在如果我只想在{{oprocessed中的oitems列的值中找到总和的话1}}表格为0

我在X

之前添加以下内容吗?
where oprocessed=0

或者我应该在SELECT CASE中添加条件吗?

1 个答案:

答案 0 :(得分:1)

您的目录ID来自oitems表 - 添加     其中oprocessed = 0 这意味着这些目录编号不包含在您的结果中。

我的猜测是你因此在你的案例陈述中想要这个 - 但我不完全确定这背后的规范,所以不能肯定地说。

select catalogid
, sum(numitems) numitems
, sum(allitems) - sum(numitems) ignoreditems
from 
(
    select i.catalogid
    , numitems allitems
    , case 
        when --if the money for the order is gaurenteed return the number of items bought
        (
            ocardtype in ('PayPal','Sofort') 
            OR
            (
                ocardtype in ('mastercard','visa') 
                and
                odate is not null
            )
        ) 
        AND NOT EXISTS 
        (
            select top 1 1
            FROM bookedordersids b
            where b.booked = o.orderid
        )
        and i.oprocessed = 0
        then numitems
        else 0 --if payment isn't made/gaurenteed 0 items bought
    end numitems
    from orders o
    inner join oitems i 
    on i.orderid = o.orderid
) X
group by catalogid