2014-11-22 86 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 $抵消,$行

相關問題