问题
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