多个SELECT中的GROUP BY

时间:2016-05-26 15:22:54

标签: mysql

假设我有四张格式相同的表:

Registered  |  Score
----------------------
0           |  10
1           |  5
1           |  7
0           |  6

我想得到Score字段(0,1)分组的每个Registered平均值。在多个SELECT中,未分组的查询将返回单个结果作为一列四列:

SELECT t1avg.a,t2avg.b,t3avg.c,t4avg.d FROM
(SELECT AVG(score) as a FROM table1) AS t1avg,
(SELECT AVG(score) as b FROM table2) AS t2avg,
(SELECT AVG(score) as c FROM table3) AS t3avg,
(SELECT AVG(score) as d FROM table4) AS t4avg

但是如何通过注册用户和未注册用户对其进行分组以获得两个结果? :

t1avg.a  |  t2avg.b  |  t3avg.c  |  t4avg.d  |  Registered
--------------------------------------------------
8        |  4.5      |  8        |  4.5      |  0
--------------------------------------------------
6        |  6.5      |  5        |  6        |  1

1 个答案:

答案 0 :(得分:1)

您需要对子查询进行分组,然后将它们进行匹配。确保它们都具有0和1值,否则您将需要LEFT OUTER JOIN而不是内连接。

SELECT t1avg.a,t2avg.b,t3avg.c,t4avg.d, t1avg.registered FROM
(SELECT AVG(score) as a, registered FROM table1 GROUP BY registered) AS t1avg,
(SELECT AVG(score) as b, registered FROM table2 GROUP BY registered) AS t2avg,
(SELECT AVG(score) as c, registered FROM table3 GROUP BY registered) AS t3avg,
(SELECT AVG(score) as d, registered FROM table4 GROUP BY registered) AS t4avg
WHERE t1avg.registered=t2avg.registered and 
t1avg.registered=t3avg.registered and 
t1avg.registered=t4avg.registered