[英]How to subtract two calculated fields from the same table in MySQL?
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
If I omit (totalcost - totalrevenue) as profit
the query works fine. 如果我忽略
(totalcost - totalrevenue) as profit
则查询工作正常。 How could I calculate PROFIT in the same query using totalcost and totalrevenue? 如何使用totalcost和totalrevenue在同一查询中计算利润?
The answer to your question is that you have to repeat the expressions: 您问题的答案是必须重复以下表达式:
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;
You are not allowed to use a column alias in the same select
where it is defined. 不允许在定义别名的同一
select
中使用列别名。
And, your query looks weird. 而且,您的查询看起来很奇怪。 Any query that has
select *
and group by
is suspect. 任何具有
select *
和group by
查询都是可疑的。 You have many columns (presumably) whose value will come from an indeterminate row for each group. 您有许多列(大概),其值将来自每个组的不确定行。 You should explicitly list the columns in general, but you should especially do so for a
group by
. 通常,您应该显式列出各列,但对于
group by
则应特别列出。
You can do like this SELECT * , (totalcost - totalrevenue) AS profit FROM( SELECT *, SUM(price+shipping+paypalfee+storefee) AS totalcost, customerpaid AS totalrevenue, 您可以这样执行:SELECT *,(总成本-总收入)AS利润,FROM(SELECT *,SUM(价格+运费+ Paypalfee +商店费用)AS总成本,客户支付的AS总收入,
FROM tblsales GROUP BY orderno HAVING " . $having . " ORDER BY $sort $order ) LIMIT $offset,$rows 从tblsales GROUP BY orderno拥有“。$ having。” ORDER BY $ sort $ order)LIMIT $ offset,$ rows
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.