如何获得 MySQL 返回的“利润”值。totalCost 和 totalSell 从数据库中获取。
select
sum(cost) as totalCost
, sum(sell) as totalSell
, (totalSell-totalCost) as profit
from orders
您为什么不尝试直接计算利润而不是使用别名?
试试这个:
Select SUM(cost) AS totalCost
, SUM(sell) AS totalSell
, (SUM(sell) - SUM(cost)) AS profit
FROM orders
您不能在select
声明它们的查询部分中使用别名:
select sum(cost) as totalCost,
sum(sell) as totalSell,
sum(sell) - sum(cost) as profit
from orders
如果您想使用别名来执行此操作(出于某种原因),您可以在子查询中定义它们时这样做:
select *, totalCost - totalSell as profit
from ( select sum(cost) as totalCost,
sum(sell) as totalSell,
from orders ) t
不要对别名执行操作。您需要更改(totalSell-totalCost)
为 (sum(cost)-sum(sell))
Select sum(cost) as totalCost , sum(sell) as totalSell, (sum(cost)-sum(sell)) as profit
from orders