I need a query that subtracts or adds according to a condition for SQLite using the CASE statement. This is my query at the moment:
SELECT s.companyName, CASE ia.type
WHEN ia.type='add' THEN SUM(ia.quantity)
WHEN ia.type='subtract' THEN SUM(-ia.type)
ELSE SUM(0) END AS total
FROM stocktake s
LEFT JOIN stocktake_adjustment sa ON s.stocktakeId = sa.stocktakeId
LEFT JOIN adjustment a ON a.adjustmentId = sa.adjustmentId
LEFT JOIN inventory_adjustment ia ON ia.adjustmentId = a.adjustmentId
LEFT JOIN inventory i ON i.inventoryId = ia.inventoryId
LEFT JOIN supplier s ON s.supplierId = i.supplierId
WHERE s.supplierId = '4da99b63-fcb9-9b9f-8415-4896caeb920c';
Basically I want to add if the condition is ‘add’ or subtract if condition is subtract, from the total.
Thank you in advance guys.
Move your
CASEintoSUM:(I assumed that
-ia.typein the original question was a typo, really meaning-ia.quantity)