[英]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
如果我忽略(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
則應特別列出。
您可以這樣執行:SELECT *,(總成本-總收入)AS利潤,FROM(SELECT *,SUM(價格+運費+ Paypalfee +商店費用)AS總成本,客戶支付的AS總收入,
從tblsales GROUP BY orderno擁有“。$ having。” ORDER BY $ sort $ order)LIMIT $ offset,$ rows
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.