1

如何获得 MySQL 返回的“利润”值。totalCost 和 totalSell 从数据库中获取。

select 
  sum(cost) as totalCost
  , sum(sell) as totalSell
  , (totalSell-totalCost) as profit 
from orders
4

3 回答 3

4

您为什么不尝试直接计算利润而不是使用别名

试试这个:

Select SUM(cost) AS totalCost
     , SUM(sell) AS totalSell
     , (SUM(sell) - SUM(cost)) AS profit
FROM orders

看到这个 SQLFiddle

于 2013-04-19T04:07:33.297 回答
1

您不能在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
于 2013-04-19T04:07:15.410 回答
1

不要对别名执行操作。您需要更改(totalSell-totalCost)(sum(cost)-sum(sell))

 Select sum(cost) as totalCost  , sum(sell) as totalSell, (sum(cost)-sum(sell)) as profit
     from orders
于 2013-04-19T04:07:57.833 回答