2014-11-22 56 views
2
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查询工作正常。如何使用总成本和总收入在同一查询中计算PROFIT?如何从MySQL中的同一个表中减去两个计算的字段?

回答

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

+0

感谢您的解决方案。请问为什么我应该明确地使用列名?我的意思是背后的逻辑。 – 2014-11-22 14:02:11

+0

@BubbaYakoza。 。 。你明白'group by'是什么吗?在'select'列中有不在'group by'列表中的列通常没有意义。也许关于扩展的文档将有助于:http://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html。 – 2014-11-22 14:04:21

0

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

FROM tblsales GROUP BY orderno 有 “$有。” ORDER BY $ $排序顺序) LIMIT $抵消,$行

相关问题