Skip to content
Advertisement

Issue with joins — would someone please explain to me what I am doing wrong?

I have two tables member and team with the structure shown below. I am trying to achieve these two results:

  1. The number of players on each team plus the total amount of fees collected for each team (ie PlayerFee times number of players).

Schema:

I have tried this below code for question 1 but I am not sure that the result I am getting is the right one.

The question number 1 has been solved but unsure how to use the COUNT function using the JOIN. any help would be much appreciated.

Advertisement

Answer

I like to use TDQD — Test-Driven Query Design — to solve complex SQL queries. These aren’t particularly hard queries, but the idea still allows you to get the right results.

Query 1 — Number of members who attend practice on each day of the week

The query must establish which night each player attends practice, and then count the number of players attending on a given night.

Step 1 — Which night do members attend practice?

Step 2 — How many players attend practice on each day of the week?

Note that this does not guarantee any order for the output. Adding ORDER BY p.PracticeNight would yield the data in the sequence Friday, Monday, Saturday, Sunday, Thursday, Tuesday, Wednesday because it would be alphabetic order. You’d have to introduce a DayOfWeekNumber for each day of the week, with or example, 0 for Sunday to 6 for Saturday, or 1 for Monday and 7 for Sunday, depending on your preferences.

Note that this query does not produce a zero for days when no team practices, or for days on which the only teams that practice on the day have no members. Fixing that is considerably harder, and requires a list of possible days of the week somewhere so that it’s possible to ensure that all days are represented in the output.

Query 2 — Number of players on each team and total fees collected per team

The ‘total fees’ part is simply the count of the number of players on each team multiplied by the team’s player fee.

Step 1 — Which players are on each team?

Step 2 — How many players are on each team?

Step 3 — And the total fees?

Step 4 — And teams with no players?

Teams with no members will not be included in the output. To get zeros for such teams, use a LEFT OUTER JOIN (which can be abbreviated to LEFT JOIN):

The COUNT aggregate does not count NULL values when you specify a column name. When there is no member for a team (TeamA suffers this indignity in the sample data), the LOJ generates a NULL for m.MemberID, so COUNT(m.MemberID) generates 0.

Warning: None of the SQL above has been tested; there could be bugs!

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement