2014-03-06 54 views
1

的兩個結果,這是我的查詢:添加兩個別名

在查詢中有來自求和許多成果,這些總和希望得到它們之間的比例,因此我要指派一個變量,這個解決方案

嘗試,因爲我不能加起來別名,我想補充 2作爲,1爲b形式的+ b AS結果...同樣查詢頭

Select a.*, SUM(a.val1) AS val1, SUM(b.val2) AS val2 
from quest1 a , quest2 b 

我想這樣做:

Select a.*, @N:= SUM(a.val1) AS val1, @M:= SUM(b.val2) AS val2, 
(100*@N/@M) as percent 
from quest1 a , quest b 
+0

是否真的使用要求變量? –

回答

1

你可以做一個子查詢不變量使用聚合函數沒有GROUP BY子句

SELECT t.*, 
(100 * (t.val1/t.val2)) `percent` 
FROM 
(
Select a.*,SUM(a.val1) AS val1, 
SUM(b.val2) AS val2 
from quest1 a , quest b 
) t 

Select a.*, 
SUM(a.val1) AS val1, 
SUM(b.val2) AS val2, 
(100 * (SUM(b.val1)/SUM(b.val2))) `percent` 
FROM quest1 a , quest b 

注實現,這將導致單列

+0

在那裏丟失一個FROM – Mihai

+0

@Mihai感謝您更新了這一點 –