2014-10-09 101 views
1

我有两个或多或少相同表:SQL AVG功能

test_score

id int(11) PK AI 
user_id int(11) 
module_id int(11) 
score double 
number_correct int(11) 
correct_total int(11) 
timestamp datetime 
phase_id int(11) 
medal_id int(11) 
team_id int(11) 
status_id int(11) 

而且

id int(11) PK AI 
user_id int(11) 
module_id int(11) 
score double 
number_correct int(11) 
correct_total int(11) 
timestamp datetime 
phase_id int(11) 
medal_id int(11) 
team_id int(11) 
status_id int(11) 

现在这两个如此相同的原因是,他们包含我系统中每个组件的数据。

现在我想使用AVG()函数来查找这两个表的平均得分合并。

这是可能的吗?

+0

创建'union'的图,使用'AVG()'上的视图。或者在'union'上没有view,'avg()'函数。 – 2014-10-09 12:15:33

+0

您使用的是什么RDBMS? – 2014-10-09 12:19:15

回答

4
SELECT user_id, average_score = AVG(score) 
FROM (
    SELECT user_id, score FROM test_score1 
    UNION ALL 
    SELECT user_id, score FROM test_score2 
) AS subquery 
GROUP BY user_id 
+0

你能解释一下test_score1和test_score2吗? – 2014-10-09 12:27:29

+0

这些是具有相同模式的表的名称。 – 2014-10-09 12:33:10

3

停止思考表格,而是“结果集”。

把问题分解成两个分量..

首先,我如何创建我从这两个表所需数据的“结果集”? 最简单的解决方案中,工会语句

select * from <table1> 
union 
select * from <table2> 

现在,取上述结果集,并计算平均

select xx.module_id,avg(xx.score) as AvgModuleScore 
from 
(
    select * from <table1> 
    union 
    select * from <table2> 
) xx 
+0

你应该使用'UNION ALL'。是的,我们似乎是针对具有主键或唯一键的表进行选择,但如果不是,那么UNION语句的隐式“DISTINCT”会歪曲AVG()的结果。 – 2014-10-09 12:25:56

+0

感谢Bacon Bits,好点... – Sparky 2014-10-09 13:11:24