【问题标题】:SQL Sum with conditions in a select caseSQL Sum 与选择案例中的条件
【发布时间】:2012-10-20 01:13:34
【问题描述】:

有以下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 张桌子 订单和商品表

查询根据您看到的条件对numitemsignoreditems 求和,现在如果我只想在oitems 表中名为oprocessed 的列的值为0 时找到总和怎么办,

我在X之前添加以下内容

where oprocessed=0

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

【问题讨论】:

  • "现在如果我只想找到总和怎么办..."。要检查,您指的是哪个总和 - 构成被忽略项目的总和,用于 numitems 的总和(这会影响被忽略),还是其他一些数字/结果?
  • 当 oprocessed 为 0 时,我想在两个总和中都忽略它
  • 您是否希望 allitems 的值也受到影响?
  • 不,我不希望所有项目受到影响,我想 WHERE oprocessed=0 是正确的使用方法,对吧?
  • 如果您放入 where 子句,则 allitems 将被更新 - 因为 where 适用于所有目录 id、numitems(作为 allitems 返回)和 case 语句。如果在 case 语句中添加条件,则只会影响 numitems 的总和(作为 numitems 返回)。

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


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多