使用SQLite中的CASE条件在总计中添加或减去

时间:2013-01-21 20:50:49

标签: sql sqlite

我需要一个使用CASE语句根据SQLite的条件减去或添加的查询。这是我目前的询问:

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'; 

基本上我想在条件为'add'时添加,或者在条件减去的情况下从总数中减去。

先谢谢你们。

2 个答案:

答案 0 :(得分:2)

CASE移至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';

(我假设原始问题中的-ia.type是拼写错误,真的意思是-ia.quantity

答案 1 :(得分:1)

我认为您需要的是在SUM中移动CASE语句,从ia.typeCASE之间删除WHEN(或更改为简单的CASE语句),并添加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;