我有一个表,想通过一些标准来使用'Sum Functions‘。例如:
ProductName Type Amount
-------------------------------
ProductA 2 10
ProductB 7 10
ProductA 8 10
ProductA 8 10
ProductC 7 10
ProductA 7 10
ProductA 3 10
ProductA 7 10
ProductB 3 10
ProductB 8 10我想用这个公式对每个乘积进行分组和求和:
Product Amount = Sum( (Type7 amount)+(Type8 amount)) - Sum( (Type2 amount)+(Type3 amount))因此,我们示例的查询结果必须为:
ProductName Amount
-----------------------
ProductA 20
ProductB 10
ProductC 10我有一个正在运行的查询:
SELECT CL.DEFINITION_
,ST.TRCODE
,IT.NAME
,SUM(ST.AMOUNT) AS AMOUNT
,
FROM LG_060_CLCARD CL
,LG_060_ITEMS IT
,LG_060_04_STLINE ST
WHERE IT.LOGICALREF = ST.STOCKREF
AND ST.CLIENTREF = CL.LOGICALREF
AND ST.TRCODE IN (
'2'
,'3'
,'7'
,'8'
)
GROUP BY CL.DEFINITION_
,ST.TRCODE
,IT.NAME
,
ORDER BY CL.DEFINITION_
,ST.TRCODE
,IT.NAME这个查询显示了一个类似于我们示例的第一个表单的表。我想将这个查询转换为我们示例的第二种形式。
在我们的示例中,ST.TRCODE是“类型”列。我如何按照上面提到的'Sum Function‘标准对产品进行分组?
发布于 2020-02-03 23:38:47
select ProductName,
sum(case when type in ('7', '8') then 1 when type in ('2', '3') then -1 end * Amount) AS Amount
from MyTable
group by ProductName结果
ProductName Amount
ProductA 20
ProductB 10
ProductC 10发布于 2020-02-03 23:43:26
您可以执行条件求和:
select t.ProductName,
sum(case when type in (7, 8) then amount when type in (2, 3) then -amount end) as Amount
from table t
group by ProductName;https://stackoverflow.com/questions/60042357
复制相似问题