HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMinor

How to calculate avg of some column in join?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
columnavgjoinsomecalculatehow

Problem

i have three tables

teacher

id name 
1  ali
2  reza


course

id title
1  math
2  litrature


gradetbl

id courseid teacherid grade 
1  1        1         20
2  2        1         10
3  1        2         17


the result:

teacherid avg(grade)
1         15
2         17


i try something but it did not work

Solution

All you really need to do is to 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.