MySQL单查询可能吗?

时间:2014-07-20 18:45:40

标签: mysql

我有一个MySQL声明:

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

我还有另一个MySQL声明:

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;

是否可能以及该陈述的结构如何?

提前感谢所有反馈和建议。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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