2015-11-08 31 views
0

我在MySQL中有兩個表。第一個是目錄,其中一列作爲類別,另一個表格以SP和CP作爲列。我想找到每個類別的總利潤。查找表中特定組值的總和

我無法想出適當的查詢。我嘗試的每個查詢都會給出錯誤。誰能幫忙?

select A.Category,sum(B.SP group by A.Category) as TotalSP,sum(B.CP group by A.Category) as TotalCP, 
case 
when TotalSP>TotalCP then ((TotalSP-TotalCP)/TotalSP)*100 
when TotalSP<TotalCP then ((TotalSP-TotalCP)/TotalCP)*100 
end 
as TotalProfit 
from Catalog A,Stock B; 

注:負利潤自動被視爲損失。

+0

你有什麼錯誤? – Mureinik

+0

@德魯'每個查詢我嘗試給出錯誤' –

回答

0
select A.Category,sum(B.SP) as TotalSP,sum(B.CP) as TotalCP, 
case 
when TotalSP>TotalCP then ((TotalSP-TotalCP)/TotalSP)*100 
when TotalSP<TotalCP then ((TotalSP-TotalCP)/TotalCP)*100 
end 
as TotalProfit 
from Catalog A 
INNER JOIN Stock B ON B.catalog_id = A.id/*Write how your tables linked here*/ 
group by A.Category; 

此查詢選擇所有目錄記錄,連接各組股票的數據,然後組結果進行分類,計數總和。

+0

感謝您的答.. @ vp_arth –