MySQL查询根据动态数据获取列

时间:2013-04-19 04:06:11

标签: mysql sql

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

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

3 个答案:

答案 0 :(得分:4)

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

试试这个:

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

See this SQLFiddle

答案 1 :(得分: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

答案 2 :(得分:1)

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

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