所有受试者的平均值除外

时间:2016-01-20 13:49:20

标签: sql oracle plsql average

我有一张像

这样的表格
Student Subject Marks
John    Maths   80
John    Science 70
John    Social  90
Raju    Maths   90
Raju    Science 80
Raju    Social  70

我希望所有受试者的平均数学和其他所有受试者的平均值如下所示,使用"有"子句。

我想要这样的O / P

Subject                   Average

Maths                       85

Rest(of all subjects)       77.5

4 个答案:

答案 0 :(得分:2)

使用CASE:

SELECT
   CASE
     WHEN Subject = 'Math' THEN Subject 
     ELSE 'All Subjects'
   END,
   AVG(Marks)
FROM tab
GROUP BY
   CASE
     WHEN Subject = 'Math' THEN Subject 
     ELSE 'All Subjects'
   END

答案 1 :(得分:1)

case语句可以用作分组字段,如下所示:

select CASE subject WHEN 'Maths' THEN subject ELSE 'Others' END as Subject, 
       AVG(Marks) as Average
from tbl
group by CASE subject WHEN 'Maths' THEN subject ELSE 'Others' END

希望有所帮助。

答案 2 :(得分:1)

使用CASE表达式在派生表中进行主题替换。然后对它进行GROUP BY的结果:

select subject, avg(marks)
from 
(
    select case when Subject <> 'Maths' then 'Rest(of all subj)' else subject end,
           Marks
    from tablename
) dt
group by subject

(核心ANSI SQL-99,加上F591,“派生表”功能。)

没有CASE

select Subject, avg(marks)
from
(
select Subject, marks from tablename where Subject = 'Maths'
union all
select 'Rest(of all subj)', marks from tablename where Subject <> 'Maths'
)
group by Subject

或者甚至更简化,正如dnoeth所建议的那样:

select 'Maths' as Subject,  avg(marks) from tablename where Subject = 'Maths'
union all
select 'Rest(of all subj)', avg(marks) from tablename where Subject <> 'Maths'

答案 3 :(得分:1)

条件聚合的另一种方式。当然,它可能会混淆一些。

AVG(1,2,NULL) = 1.5 1因为,聚合函数排除 NULL

SELECT
   AVG(CASE
     WHEN Subject = 'Maths' THEN Marks 
     ELSE NULL
   END) "Maths",
 AVG(CASE
     WHEN Subject = 'Maths' THEN NULL 
     ELSE Marks
   END)  "Rest Of All"
FROM tab
相关问题