Paren Mwelase
Paren Mwelase

Reputation: 25

Add or subtract from total using CASE conditions in SQLite

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.

Upvotes: 0

Views: 3991

Answers (2)

GarethD
GarethD

Reputation: 69789

I think what you need is to move the CASE statement inside the SUM, remove ia.type from between CASE and WHEN (or change to a simple CASE statement), and also add GROUP BY:

SELECT  s.companyName, 
        SUM(CASE WHEN ia.type = 'add' THEN ia.Quantity 
                WHEN ia.type = 'subtract' THEN -ia.Quantity 
                ELSE 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'
GROUP BY s.CompanyName; 

Upvotes: 1

Anton Kovalenko
Anton Kovalenko

Reputation: 21507

Move your CASE into SUM:

SELECT s.companyName, SUM(CASE ia.type 
                          WHEN ia.type='add' THEN ia.quantity
                          WHEN ia.type='subtract' THEN -ia.quantity 
                          ELSE 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';

(I assumed that -ia.type in the original question was a typo, really meaning -ia.quantity)

Upvotes: 2

Related Questions