如何从MySQL中的同一个表中减去两个计算字段?

时间:2014-11-22 13:49:33

标签: mysql sql

SELECT   *, 
         SUM(price+shipping+paypalfee+storefee) AS totalcost, 
         customerpaid                           AS totalrevenue, 
         (totalcost - totalrevenue)             AS profit 
FROM     tblsales 
GROUP BY orderno 
HAVING   " . $having . " 
ORDER BY $sort $order 
LIMIT    $offset,$rows

如果我省略(totalcost - totalrevenue) as profit,查询工作正常。如何使用totalcost和totalrevenue在同一查询中计算PROFIT?

2 个答案:

答案 0 :(得分:3)

你的问题的答案是你必须重复这些表达:

select *, sum(price+shipping+paypalfee+storefee) as totalcost
       customerpaid as totalrevenue,
       (sum(price+shipping+paypalfee+storefee) - customerpaid) as profit
from tblsales
group by orderno
having " . $having . "
order by $sort $order
limit $offset, $rows;

您不能在定义它的同一select中使用列别名。

并且,您的查询看起来很奇怪。任何包含select *group by的查询都是可疑的。您有许多列(大概),其值将来自每个组的不确定行。您应该明确列出一般的列,但您应该特别为group by

这样做

答案 1 :(得分:0)

你可以这样做 SELECT *,(totalcost - totalrevenue)AS利润来自( 选择 *,          SUM(价格+运费+ paypalfee + storefee)AS totalcost,          customerpaid AS totalrevenue,

FROM tblsales GROUP BY orderno 有“。有钱。” 订购$ sort $ order) LIMIT $ offset,$ rows