简体   繁体   中英

How to get average for each student in sql?

I have 2 tables - Table1 and Table2 :

Student ID   Student Name
-------------------------
12           John Smith
14           Raj Sharma
15           Lee Wang
16           Anan Obi

Student ID   Course           Points
-------------------------------------
12           Mathematics      86
14           Mathematics      75
16           Mathematics      96
16           Mathematics      97
15           Physics          92
15           Physics          65
12           Physics          63
16           Physics          58
14           Physics          78
14           Chemistry        83
15           Chemistry        65
12           Chemistry        95
12           Chemistry        90

I want to get average points per course for each student, sorted by student names.

Resulting output should be:

| name       | course | avg (points) |
+------------+--------+--------------+
| Anan Obi   | Math   | 96.50000     |
| Anan Obi   | Phys   | 58.00000     |
| John Smith | Math   | 86.00000     |
| John Smith | Phys   | 63.00000     |
| John Smith | Chem   | 92.50000     |
| Lee Wang   | Phys   | 78.50000     |
| Lee Wang   | Chem   | 65.00000     |
| Raj Sharma | Math   | 75.00000     |
| Raj Sharma | Phys   | 78.00000     |
| Raj Sharma | Chem   | 83.00000     |

I tried the following code but not getting desired output:

select 
    t1.'student name', 
    t2.'course', avg(points) 
from 
    table1 t1, table2 t2 
group by 
    t2.Course 
order by 
    t1.'student name'

Any help is appreciated.

Thanks

Group by also over course

select s.[Student ID], s.[Student Name], sc.course, avg(sc.Points) 
from Students s
JOIN studentsCourse sc ON s.[Student ID]= sc.[Student ID]
Group by s.[Student ID], s.[Student Name], sc.course
order by s.[Student Name]

Very simple by using Window Functions

select t1.Student Name, avg(t2.Points) over (partition by t1.Student Name,t2.course)

from t1 left join t2 on t1.Student ID=t2.Student ID

select s.name, sc.course,r.avg(Points) 
from Students s
JOIN studentsCourse r ON s.id= e.id
Group by r.course
order by s.name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM