snippetsqlMinor
How to calculate avg of some column in join?
Viewed 0 times
columnavgjoinsomecalculatehow
Problem
i have three tables
teacher
course
gradetbl
the result:
i try something but it did not work
teacher
id name
1 ali
2 rezacourse
id title
1 math
2 litraturegradetbl
id courseid teacherid grade
1 1 1 20
2 2 1 10
3 1 2 17the result:
teacherid avg(grade)
1 15
2 17i try something but it did not work
Solution
All you really need to do is to
For the results you have indicated there should be no need to use a
You should view the documentation for SELECT, GROUP BY and AVG for thorough examples and explanations of common usage.
SELECT from the gradetbl, apply the AVG aggregate function over the grade and then GROUP BY the teacherid like so:SELECT teacherid, AVG(grade)
FROM gradetbl
GROUP BY teacherid;For the results you have indicated there should be no need to use a
JOIN at all. You will only need to use a JOIN when you want to fetch data associated with the teacherid:SELECT t.name, AVG(g.grade)
FROM gradetbl AS g
JOIN teacher as t
ON t.id = g.teacherid
GROUP BY t.name;You should view the documentation for SELECT, GROUP BY and AVG for thorough examples and explanations of common usage.
Code Snippets
SELECT teacherid, AVG(grade)
FROM gradetbl
GROUP BY teacherid;SELECT t.name, AVG(g.grade)
FROM gradetbl AS g
JOIN teacher as t
ON t.id = g.teacherid
GROUP BY t.name;Context
StackExchange Database Administrators Q#171700, answer score: 6
Revisions (0)
No revisions yet.