2014-10-09 58 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