[英]SQL Sum with conditions in a 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
现在我有2张桌子这里的订单和oitems表
查询将根据您看到的条件对数字numitems
和被ignoreditems
求和,现在,如果我仅在oitems
表中名为oprocessed
的列的值为0
时才想查找总和,该oprocessed
oitems
我在X
之前添加以下内容吗
where oprocessed=0
还是应该向SELECT CASE添加条件?
您的目录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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.