2017-05-04 61 views
2

我試圖獲得所有具有乘以兩列值的行的總和,以及條件但是獲取了一些mysql錯誤。嘗試過了一些例子,我實現我的結果,但我不知道這是正確的方式或不:MySQL:代表第三列獲得乘以兩列的列的總和

表:store_stocks

enter image description here

我只是想乘算庫存數量與金額數量根據含增值稅,不含增值稅和總庫存。

我剛剛創建的查詢:

SELECT sum(qty*sale_price) as total_stock, 
(select sum(qty*sale_price) from store_stocks where vat_status = 0 and store_id = 8) as non_vat_stock, 
(select sum(qty*sale_price) from store_stocks where vat_status = 1 and store_id = 8) as with_vat_stock 
FROM `store_stocks` where store_id = 8 group by store_id 

其顯示結果:

enter image description here

任何一個可以告訴我有沒有另一種方式來做到這一點,因爲我認爲這是查詢有點複雜,每次我使用子查詢中的位置,我也必須在laravel eloquent中實現此查詢。

回答

1

你不需要的子查詢,你可以使用條件的sum()內,使其只總結了特定的記錄:

SELECT sum(qty*sale_price) as total_stock, 
     sum(if(vat_status = 0, qty*sale_price, 0)) as non_vat_stock, 
     sum(if(vat_status = 1, qty*sale_price, 0)) as with_vat_stock 
FROM `store_stocks` where store_id = 8 group by store_id 

您可以使用,而不是if()功能case表達。

+0

其在第2行顯示錯誤'as non_vat_stock, sum(if(vat_status = 1,qty * sale_price,0)as with_vat' –

+0

錯誤關閉')'兩次。但是,請不要複製粘貼解決方案,也要嘗試理解它。 – Shadow

+0

哇..大!! –