473,425 Members | 1,673 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,425 software developers and data experts.

3 table query

Hi Everyone!
I have three tables which i need to query. Here is their format:

Team
TeamID
TeamName

CoachTeam
CoachID
TeamID

PlayerTeam
PlayerID
TeamID

I need to get a list of Teams for a Coach, and that list needs to have a column for Number of Players on that team.
I can get a list of teams of a coach, and i can get the number of players for a team individually, but I don't know how to combine those two queries to give me 1 table.
What would be the best way to achieve this? Thanks in advance!
Sep 4 '10 #1

✓ answered by NeoPa

It seems I missed out the GROUP BY clause of the CTE. As CK says, the CTE is a definition (referred to later by the name - cteNumPlayers). This can be considered as very similar to a subquery, but instead of being defined inline, as a subquery is, it is declared up front, and referred to within the main SQL by name. I've included the updated version below :
Expand|Select|Wrap|Line Numbers
  1. WITH cteNumPlayers AS
  2. (
  3.     SELECT   [TeamID]
  4.            , COUNT(*) AS [NumPlayers]
  5.     FROM     [PlayerTeam]
  6.     GROUP BY [TeamID]
  7. )
  8. SELECT   tCT.CoachID
  9.        , tT.TeamName
  10.        , cNP.NumPlayers
  11. FROM    ([CoachTeam] AS [tCT]
  12.          INNER JOIN
  13.          [Team] AS tT
  14.   ON     tCT.TeamID = tT.TeamID)
  15.          LEFT JOIN
  16.          [cteNumPlayers] AS cNP
  17.   ON     tCT.TeamID = cNP.TeamID
  18. ORDER BY tCT.CoachID
  19.        , tCT.TeamID
All that said, of course, CK may have a point with his simpler overall GROUP BY offering. It only uses two of the three tables, but I suspect it could be got to work as required. I couldn't think how when I first looked at the problem, but maybe I just overlooked the simple (as I have a habit of doing sometimes :D)

Anyway, as a last point, we don't normally allow members to select their own posts as best answer. Exceptions might be if they went off, without help from other members, and researched and posted their solutions. This clearly isn't the case here, so apologies, but I had to reset that.

8 1475
gpl
152 100+
What do your 2 queries look like ?
Sep 6 '10 #2
NeoPa
32,556 Expert Mod 16PB
I'd start with a CTE (Common Table Expression) for the subquery (See Subqueries in SQL) which counts the players in the team, then, when you have three record sources that all work at the same level simply join them together :

Expand|Select|Wrap|Line Numbers
  1. WITH cteNumPlayers AS
  2. (
  3.     SELECT [TeamID]
  4.          , COUNT(*) AS [NumPlayers]
  5.     FROM [PlayerTeam]
  6. )
  7. SELECT   tCT.CoachID
  8.        , tT.TeamName
  9.        , cNP.NumPlayers
  10. FROM    ([CoachTeam] AS [tCT]
  11.          INNER JOIN
  12.          [Team] AS tT
  13.   ON     tCT.TeamID = tT.TeamID)
  14.          LEFT JOIN
  15.          [cteNumPlayers] AS cNP
  16.   ON     tCT.TeamID = cNP.TeamID
  17. ORDER BY tCT.CoachID
  18.        , tCT.TeamID
You may well have a [Coach] table too if I guess aright, but fitting that in should be simple enough. Ask if you need help though.
Sep 6 '10 #3
@NeoPa

The first part of that SQL did not execute.
# WITH cteNumPlayers AS
# (
# SELECT [TeamID]
# , COUNT(*) AS [NumPlayers]
# FROM [PlayerTeam]
# )

Here is the original table PlayerTeam

PlayerTeam
TeamID - UserID
1 - 22
1 - 11
1 - 10
2 - 15

And here is how it should be pivoted

PlayerTeamPivoted

TeamID NumPlayers
1 - 3
2 - 1

I read up on the PIVOT command in MSDN, but am thoroughly confused on how to use it. I know the aggregate function i need is COUNT, but what do i put after IN for the pivot sql?
Sep 9 '10 #4
ck9663
2,878 Expert 2GB
You can not run the WITH part with running the second select. It should be executed both.

You may want to also try this:

Expand|Select|Wrap|Line Numbers
  1.  
  2. select c.CoachId, p.TeamId, count(*)
  3. from PlayerTeam p
  4. inner join CoachTeam c on p.TeamId = c.TeamId
  5. group by c.CoachId, p.TeamId
  6.  
  7.  
Happy Coding!!!

~~ CK
Sep 9 '10 #5
Alrite, so here is my first query:

Expand|Select|Wrap|Line Numbers
  1. SELECT tblCoachTeam.UserID, tblTeam.TeamID
  2. FROM tblCoachTeam
  3. INNER JOIN tblTeam ON tblCoachTeam.TeamID = tblTeam.TeamID
  4. WHERE tblCoachTeam.UserID = @UserID
This gives me the list of teams for a coach.

The second part of the query is:
Expand|Select|Wrap|Line Numbers
  1. SELECT TeamID, COUNT(UserID) AS [NumPlayers]
  2.     FROM dbo.tblPlayerTeam
  3.     GROUP BY TeamID
This gives me the number of players on each team.

Now I have joined them with this:


Expand|Select|Wrap|Line Numbers
  1. WITH cteNumPlayers AS
  2. (
  3.     SELECT TeamID, COUNT(UserID) AS [NumPlayers]
  4.     FROM dbo.tblPlayerTeam
  5.     GROUP BY TeamID
  6. )
  7. SELECT tblCoachTeam.UserID, tblTeam.TeamID, cteNumPlayers.NumPlayers
  8. FROM tblCoachTeam
  9. INNER JOIN tblTeam ON tblCoachTeam.TeamID = tblTeam.TeamID
  10. LEFT JOIN cteNumPlayers ON tblCoachTeam.TeamID = cteNumPlayers.TeamID
  11. WHERE tblCoachTeam.UserID = @CoachID
It works!

Thanks for your help everyone!!!
Sep 9 '10 #6
NeoPa
32,556 Expert Mod 16PB
It seems I missed out the GROUP BY clause of the CTE. As CK says, the CTE is a definition (referred to later by the name - cteNumPlayers). This can be considered as very similar to a subquery, but instead of being defined inline, as a subquery is, it is declared up front, and referred to within the main SQL by name. I've included the updated version below :
Expand|Select|Wrap|Line Numbers
  1. WITH cteNumPlayers AS
  2. (
  3.     SELECT   [TeamID]
  4.            , COUNT(*) AS [NumPlayers]
  5.     FROM     [PlayerTeam]
  6.     GROUP BY [TeamID]
  7. )
  8. SELECT   tCT.CoachID
  9.        , tT.TeamName
  10.        , cNP.NumPlayers
  11. FROM    ([CoachTeam] AS [tCT]
  12.          INNER JOIN
  13.          [Team] AS tT
  14.   ON     tCT.TeamID = tT.TeamID)
  15.          LEFT JOIN
  16.          [cteNumPlayers] AS cNP
  17.   ON     tCT.TeamID = cNP.TeamID
  18. ORDER BY tCT.CoachID
  19.        , tCT.TeamID
All that said, of course, CK may have a point with his simpler overall GROUP BY offering. It only uses two of the three tables, but I suspect it could be got to work as required. I couldn't think how when I first looked at the problem, but maybe I just overlooked the simple (as I have a habit of doing sometimes :D)

Anyway, as a last point, we don't normally allow members to select their own posts as best answer. Exceptions might be if they went off, without help from other members, and researched and posted their solutions. This clearly isn't the case here, so apologies, but I had to reset that.
Sep 10 '10 #7
@NeoPa

Thanks for your reply!

regarding last point:
I was not sure which post i should mark as "best answer", since they all added a little bit to the solution. So I just posted the complete solution and made sure to thank everyone for their efforts. =)

I guess I will choose yours now since you have corrected it. Thanks!
Sep 10 '10 #8
NeoPa
32,556 Expert Mod 16PB
You make a good point, but as these are also used (main point really is to help a browser to go straight to a good answer of course) to rate members for how useful their answers are, then we like to avoid the situation where OPs get their help then flag their own posts as Best Answer (even though it may be the one where all the points are pulled together as it were).
Sep 11 '10 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Rich N | last post by:
I want to move several records from one table to a new table. My database is set up so that there's the "regular" database, and the ".be" database. In which do I use the Make Table Query?
1
by: PMB | last post by:
Thank you in advance for any and all assistance. I'm trying to use a make table query to pull the last transactionID, so I can use an append query to reset the transactionID to the next...
4
by: Oreo Bomb | last post by:
I have a secured database that contains a Read-Only group. This group has permissions to view reports, but cannot add, edit, or delete any DB objects. One of the reports the group needs access to...
2
by: Kathy Krizl | last post by:
I'm probably doing something stupid, but I have a make table query. One of the tables I reference has some check box fields in it. Their Data Type is Yes/No, their field property format is Yes/No,...
2
by: Dragon | last post by:
When I run a make-table query, the results take over 1 minute to return. The query is making a table that has 12,000 records in it. If I run the make-table query ONLY to see the records that will...
4
by: Alan Lane | last post by:
Hello world: I'm including both code and examples of query output. I appologize if that makes this message longer than it should be. Anyway, I need to change the query below into a pivot table...
4
by: ken | last post by:
Hi, I use this command to run a make table query without opening it... CurrentDb.Execute "make table query name" Access tells me that it can't execute a select query...? Its a make table query...
3
by: Robertf987 | last post by:
Hi, I'm a bit stuck with an access database. I'm using access 2000 if that's any help. Right, it's 3:40am right now and I'm rather tired, but I *hope* this makes sense. I have a table which...
27
by: MLH | last post by:
How can I turn the following into a make-table query? SELECT & " " & AS Recipient FROM tblVehicleJobs INNER JOIN tblAddnlOwnrs ON tblVehicleJobs.VehicleJobID = tblAddnlOwnrs.VehicleJobID WHERE...
2
by: Laurel | last post by:
I am completely new to access. I have a make-table query that combines data from two/more tables, asks for a criteria, deletes the old table and produces a new table every time under the same name....
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.