1

I have a database structure like this:

Table - lodges
LodgeID (PK)
Lodge
etc

Table - scores
ScoreID (PK)
Score
CategoryID
LodgeID (FK)

I'm trying to return results in the form:

LodgeID, Lodge, Category, Number of Scores in that Category, Average Score in that Category

So for example, if I had:

lodges

LodgeID, Lodge
1, Lodge One
2, Lodge Two

scores

ScoreID, Score, CategoryID, LodgeID
1, 3, 101, 1
2, 5, 101, 1
3, 7, 101, 1
4, 10, 102, 2
5, 20, 102, 2
6, 30, 102, 2
7, 40, 102, 2

I'd like to return:

1, Lodge One, 3, 5
2, Lodge Two, 4, 25

I've been trying things like:

SELECT        COUNT(ScoreID) as scoreCount, AVG(Score) as AverageScore, Lodge 
FROM          scores_temp 
INNER JOIN    lodges_temp ON scores_temp.LodgeID = lodges_temp.LodgeID

SELECT lodges_temp.LodgeID, Lodge, COUNT(ScoreID) as scoreCount, AVG(Score) as AverageScore FROM lodges_temp INNER JOIN scores_temp ON lodges_temp.LodgeID = scores_temp.LodgeID

Without any success. Any pointers would be much appreciated.

2
  • 1
    You should look into GROUP BY. Commented Aug 19, 2014 at 15:17
  • did you add Group By Lodge at the end? Commented Aug 19, 2014 at 15:17

2 Answers 2

1

Try this

SELECT        COUNT(ScoreID) as scoreCount, AVG(Score) as AverageScore, Lodge 
FROM          scores_temp 
INNER JOIN    lodges_temp ON scores_temp.LodgeID = lodges_temp.LodgeID
GROUP BY Lodge
Sign up to request clarification or add additional context in comments.

Comments

0

You are missing a group by clause:

SELECT     COUNT(ScoreID) as scoreCount, AVG(Score) as AverageScore, Lodge 
FROM       scores
INNER JOIN lodges ON scores.LodgeID = lodges.LodgeID
GROUP BY   lodge

1 Comment

Thank you! I always forget about Group By!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.