[英]SQL AVG function on multiple tables
I have two more or less identical tables: 我有两个或多或少相同的表:
test_score 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)
And 和
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)
Now the reason for these two being so identical is that they contain data from each of their own component in my system. 现在,这两个原因如此相同的原因是,它们包含了我系统中每个组件的数据。
Now i want to use the AVG()
function to find the average score of these two tables combined. 现在,我想使用AVG()
函数查找这两个表相结合的平均分数。
is this possible? 这可能吗?
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
Stop thinking in terms of tables, but rather "result sets". 不要以表格的方式思考,而是以“结果集”的方式思考。
Break the problem into two components.. 将问题分为两个部分。
First, how do I create a "result set" of the data I want from these two tables? 首先,如何从这两个表中创建所需的数据“结果集”? Simplest solution, the union statement 最简单的解决方案, 联合声明
select * from <table1>
union
select * from <table2>
Now, take the above result set and compute the average 现在,采用上述结果集并计算平均值
select xx.module_id,avg(xx.score) as AvgModuleScore
from
(
select * from <table1>
union
select * from <table2>
) xx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.