获得每项测试最高分的AVG分数

时间:2017-06-26 21:43:47

标签: sql oracle max average

我在编写查询时遇到问题,该查询抓取/计算学生特定考试的三个考试成绩的平均值。请考虑以下TEST_SCORES表:

ID   Name   TestCode  Score
-----------------------------
119  Joe       MCA      108  
119  Joe       BRT      98
119  Joe       LPO      76
119  Joe       BRT      111
119  Joe       ALK      83
119  Joe       MCA      100
119  Joe       RTK      75

For my scenario, I only want to consider scores from the "MCA" test, 
the "BRT" test, and the "RTK" test. I need the average of those tests. 
Also, I want to take the highest grade received for those 
tests (This is where I get stuck at). The following is what I have
so far:

SELECT A.ID, avg(A.Score)
FROM TEST_SCORES A
WHERE A.TestCode in ('MCA','BRT','RTK')
AND A.ID = 119
GROUP BY A.ID

这名学生有一个以上的分数条目用于" BRT"测试和" MCA"测试。我试图获得每个测试的MAX测试分数。我尝试使用一个条件来获得最高分,但我最终得到的是最高的考试成绩期,而不是三次考试的平均成绩。

对此的任何帮助将不胜感激。提前谢谢。

2 个答案:

答案 0 :(得分:0)

首先获取每个ID的select[name="fontSize"] option:nth-child(1) { background: red; } 分数,然后获取testCode,然后获得max每个ID的分数。

avg

答案 1 :(得分:0)

设置不是最佳的(NAME不应出现在此表中,它应该在一个较小的查找表中,将名称与每个ID相关联,如下图所示)。

除此之外,根据您的Oracle版本(您应始终包含在您的问题中),您可能会或可能无法使用lateral子句(自Oracle 12.1以来可用)获得更有效的解决方案,在一次通过数据 - 即使你需要所有学生的平均分数,而不仅仅是一个。

另一个观察结果 - 如果学生根本没参加考试(考试代码),那么考试将不会在计算中被考虑,而不是在得分为0的情况下进行平均考试(因为通常在现实生活中的情况)。接受的答案没有处理这种可能性,下面的解决方案也没有。 如果必须处理,那么您需要澄清您的问题/要求。

with
     test_data ( id, testcode, score ) as (
       select 119, 'MCA', 108 from dual union all 
       select 119, 'BRT',  98 from dual union all
       select 119, 'LPO',  76 from dual union all
       select 119, 'BRT', 111 from dual union all
       select 119, 'ALK',  83 from dual union all
       select 119, 'MCA', 100 from dual union all
       select 119, 'RTK',  75 from dual union all
       select 200, 'ABC', 110 from dual union all
       select 200, 'LPO',  90 from dual union all
       select 200, 'BRT',  90 from dual union all
       select 200, 'ALK', 102 from dual union all
       select 200, 'LPO',  90 from dual
     ),
     students ( id, name ) as (
       select 119, 'Joe' from dual union all
       select 200, 'Ann' from dual
     )
select s.id, s.name, avgscore
from   students s,
       lateral ( select   avg(max(score)) as avgscore
                 from     test_data t
                 where    t.id = s.id
                   and    testcode in ('MCA','BRT','RTK')
                 group by testcode
               )
;

 ID  NAME  AVGSCORE
---  ----  --------
119  Joe         98
200  Ann         90
相关问题