2014-07-20 54 views
0

我有一個MySQL聲明:MySQL單個查詢可能嗎?

SELECT name, ((AVG (q1) + AVG(q2) + AVG(q3)/3) AS Average 
FROM tresults GROUP BY name ORDER BY name; 

我也有另一個MySQL statment:

SELECT name, ((AVG (q1) + AVG(q2) + AVG(q3)/3) AS Average 
FROM tresults WHERE q35 = 1 GROUP BY name ORDER BY name; 

我使用子查詢的嘗試,但因爲它返回多行下面的代碼無法正常工作:

SELECT name, ((AVG (q1) + AVG(q2) + AVG(q3)/3) AS Average, 
    (SELECT ((AVG (q1) + AVG(q2) + AVG(q3)/3) 
    FROM tresults WHERE q35 = 1 GROUP BY name ORDER BY name) AS Average2 
FROM tresults GROUP BY name ORDER BY name; 

是否可能以及該語句的結構是什麼樣子?

在此先感謝您的任何反饋意見和建議。

+0

柳可以使用UNION ALL的2個查詢之間。 – Mihai

回答

1
SELECT name, 
     (AVG (AVG (q1) + AVG(q2) + AVG(q3)/3) AS Average, 
     (AVG (AVG (case when q35 = 1 then q1 else 0 end) + 
      (AVG (case when q35 = 1 then q2 else 0 end) + 
      (AVG (case when q35 = 1 then q3 else 0 end)/3) AS q35_Average 
FROM tresults 
GROUP BY name 
ORDER BY name 
0

因爲你計算平均值的平均水平,這可能是更快地使用sum而不是使用avg功能

select name, 
    sum(q1+q2+q3)/sum(3) as average 
    sum(case when q35 = 1 then (q1+q2+q3) else 0 end) 
    /sum(case when q35 = 1 then 3 else 0 end) as q35_average 
from tresults 
group by name 
order by name