具有以下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表
查询根据您看到的条件对numitems
和ignoreditems
进行求和,现在如果我只想在{{oprocessed
中的oitems
列的值中找到总和的话1}}表格为0
,
我在X
where oprocessed=0
或者我应该在SELECT CASE中添加条件吗?
答案 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