我在MySQL中有两个表。第一个是Catalog,其中一列是Category,另一个是Stock,SP和CP作为列。我想找到每个类别的总利润。
我无法提出适当的查询。我尝试的每个查询都会出错。有人可以帮忙吗?
select A.Category,sum(B.SP group by A.Category) as TotalSP,sum(B.CP group by A.Category) as TotalCP,
case
when TotalSP>TotalCP then ((TotalSP-TotalCP)/TotalSP)*100
when TotalSP<TotalCP then ((TotalSP-TotalCP)/TotalCP)*100
end
as TotalProfit
from Catalog A,Stock B;
注意:负利润自动被视为损失。
答案 0 :(得分:0)
select A.Category,sum(B.SP) as TotalSP,sum(B.CP) as TotalCP,
case
when TotalSP>TotalCP then ((TotalSP-TotalCP)/TotalSP)*100
when TotalSP<TotalCP then ((TotalSP-TotalCP)/TotalCP)*100
end
as TotalProfit
from Catalog A
INNER JOIN Stock B ON B.catalog_id = A.id/*Write how your tables linked here*/
group by A.Category;
此查询选择所有目录记录,将库存数据加入其中,然后按类别对结果进行分组,计算每个组中的总和。