0

有以下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

现在我有 2 个表,这里有订单和 oitems 表

查询根据您看到的条件对numitems和求和ignoreditems,现在如果我只想在表中调用的列的值为 时oprocessed找到oitems总和0

我之前要添加以下内容吗X

where oprocessed=0

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

4

1 回答 1

1

您的目录 ID 来自 oitems 表 - 添加 where 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
于 2012-10-20T01:25:57.777 回答