我需要一个使用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'时添加,或者在条件减去的情况下从总数中减去。
先谢谢你们。
答案 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.type
和CASE
之间删除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;