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 在同一个查询中计算利润?
最佳答案
你的问题的答案是你必须重复这些表达:
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
,您尤其应该这样做。
关于mysql - 如何从 MySQL 中的同一个表中减去两个计算字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27078130/