I have the following sql tables
oitems table
+---------+-----------+----------+
| orderid | catalogid | numitems |
+---------+-----------+------
select catalogid, numitems, allitems - numitems ignoreditems
from (
select i.catalogid,
sum(case when (ocardtype in ('PayPal','Sofort') OR
ocardtype in ('mastercard','visa') and
odate is not null) AND NOT EXISTS (
select * from booked b
where b.ignoredoid = o.orderid
) then numitems
else 0 end) numitems,
sum(numitems) allitems
from orders o
join oitems i on i.orderid=o.orderid
group by i.catalogid
) X
Something like:
SELECT
oi.catalog_id,
SUM(CASE
WHEN ocardtype in ('Paypal','Sofort') THEN numitems
WHEN ocardtype in ('Mastercard','Visa') and odate is not null THEN numitems
ELSE 0 END) as numitems,
SUM(CASE
WHEN ocardtype is null then numitems
WHEN ocardtype in ('Mastercard','Visa') and odate is null THEN numitems
ELSE 0 END) as ignoreditems
FROM
oitems oi
inner join
Orders o
on
oi.orderid = o.orderid
GROUP BY
oi.catalog_id
(Assuming that wherever you've used the word "empty" in your narrative, you mean the column is NULL
)
Here is a Linq-to-sql version of your original request (as a LINQpad query):
Dim odateRequired = {"MasterCard", "Visa"}
Dim odateNotRequired = {"Paypal", "Sofort"}
Dim result = From o In Orders Join i In Oitems On o.orderid Equals i.orderid _
Let check = o.ocardtype IsNot Nothing _
AndAlso ((odateRequired.Contains(o.ocardtype) _
AndAlso o.odate IsNot Nothing) _
OrElse odateNotRequired.Contains(o.ocardtype)) _
Group By i.catalogid Into _
numitem = Sum(If(check, i.numitems, 0)), _
ignored = Sum(If(check, 0, i.numitems))
result.Dump
Your extra request in the comments to RichardTheKiwi's answer (it just includes Not (From b In Bookeds Where b.ignoredoid=i.orderid).Any AndAlso
at the front of the check
):
Dim odateRequired = {"MasterCard", "Visa"}
Dim odateNotRequired = {"Paypal", "Sofort"}
Dim result = From o In Orders Join i In Oitems On o.orderid Equals i.orderid _
Let check = Not (From b In Bookeds Where b.ignoredoid = i.orderid).Any _
AndAlso o.ocardtype IsNot Nothing _
AndAlso ((odateRequired.Contains(o.ocardtype) _
AndAlso o.odate IsNot Nothing) _
OrElse odateNotRequired.Contains(o.ocardtype)) _
Group By i.catalogid Into _
numitem = Sum(If(check, i.numitems, 0)), _
ignored = Sum(If(check, 0, i.numitems))
result.Dump