I use MariaDB and have two tables (orders, invoiced_positions) and I need to calculate how many of each item were invoiced and paid for. So I need to count the rows and group by item_name. The problem of this is that some of the items are reopened: so I need to subtract the number of reopened invoices from the ones that were not. Basically: I want to do for all items what I achieved here for only one item:
SELECT
(SELECT COUNT(item_name = 'Streuselkuchen')
FROM orders, invoiced_positions
WHERE order_id = id AND reopened = 0)
- (SELECT COUNT(item_name = 'Streuselkuchen')
FROM orders, invoiced_positions
WHERE order_id = id AND reopened != 0) AS Difference;
I think this can be achieved with a conditional aggregation as is shown here but I haven't been able to apply this to my specific task.