2016-07-26 60 views
-1

我想展示我的問題的例子。 因此,我有學生,他們正在不同的學校學習,我想按學校數算平均數,然後計算總平均數。SQL:甲骨文平均集團

例子:

example

所以,我怎麼能得到導致像這樣的?

在此先感謝!

還有一個選項 - 對於我來說,在一個查詢中這樣做真的很舒服。

+1

見解析函數https://docs.oracle.com/cd/B28359_01/server.111/b28286/functions001.htm#i81407 – Serg

+0

那你試試這麼遠嗎? –

+0

@tamasRev我已經嘗試過使用avg(「schoolAvg」)over(),不同的分區情況,但這並沒有幫助。 – quento

回答

1
with 
    marks (school, student, mark) as (
     select 'School 1', 'James' , 5 from dual union all 
     select 'School 1', 'Mark' , 4 from dual union all 
     select 'School 1', 'Howard', 5 from dual union all 
     select 'School 4', 'Jho' , 4 from dual union all 
     select 'School 5', 'Kate' , 5 from dual 
    ), 
    a (school, s_avg) as (
     select school, avg(mark) 
     from  marks 
     group by school 
    ) 
select school, student, mark, 
     avg(mark) over (partition by school) as avg_by_school, 
     (select avg(s_avg) from a) as global_avg 
from marks; 


SCHOOL STUDENT  MARK AVG_BY_SCHOOL GLOBAL_AVG 
-------- ------- ---------- ------------- ---------- 
School 1 James   5   4.667  4.556 
School 1 Mark    4   4.667  4.556 
School 1 Howard   5   4.667  4.556 
School 4 Jho    4   4.000  4.556 
School 5 Kate    5   5.000  4.556 

5 rows selected. 
+0

感謝您的回答! – quento