Finding an average SQL

北城以北 提交于 2020-01-30 10:34:48

问题


im trying to create an average on a rating.

i have tried the AVG(column_name). however the problem with this is it does a total for all the ratings and gives the average.

Select Company.company_id, company.Company_Name, avg(UserJobRating.Total_Rating)
from company
inner join UserJobRating on Job_id = UserJobRating.Job_ID
inner join jobs on jobs.Company_id = company.company_id
group by company.company_id

what i want is say for example, a spefic company has 10/15 jobs each with a job rating. i want it to group together the jobs specific to that company and give an average rating for the company over all their jobs.

what type of select would i need to do in order to do this?


回答1:


I'm going to guess a little bit on what's going on from your comment, so I think your JOIN is off a bit. Try this:

Select Company.company_id, company.Company_Name, avg(UserJobRating.Total_Rating)
from company
  inner join jobs on jobs.Company_id = company.company_id
  inner join UserJobRating on jobs.Job_id = UserJobRating.Job_ID
group by company.company_id
  • SQL Fiddle Demo

Without seeing your table definitions, this is a bit of a guess, but I would bet you're producing a Cartesian Product with the UserJobRating table with this statement:

on Job_id = UserJobRating.Job_ID




回答2:


Your problem is the join condition:

Select Company.company_id, company.Company_Name, avg(UserJobRating.Total_Rating)
from company
inner join UserJobRating on Job_id = UserJobRating.Job_ID
----------------------------^
inner join jobs on jobs.Company_id = company.company_id
group by company.company_id

What is happening is that company does not have a field called Job_id. So, this condition is really:

inner join UserJobRating on UserJobRating.Job_id = UserJobRating.Job_ID

Which, is essentially, a cross join rather than an inner join (the only difference is that this would filter out NULL values of job_id).

Presumably, the proper field is in the next table, so you need to rearrange the tables in the join:

Select Company.company_id, company.Company_Name, avg(UserJobRating.Total_Rating)
from company
inner join jobs on jobs.Company_id = company.company_id
inner join UserJobRating on jobs.Job_id = UserJobRating.Job_ID
group by company.company_id;

This should solve your problem.



来源:https://stackoverflow.com/questions/17914573/finding-an-average-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!