Say we have two tables in an MS Access db:
Service Users:
| ID | Name | Other details... |
| 1 | Joe | Blah... |
| 2 | Fred | Qwerty... |
| 3 | Bob | Something else...|
Teams providing services:
| ID | TeamID | UserID |
| 1 | T1 | 1 |
| 2 | T2 | 1 |
| 3 | T2 | 2 |
| 4 | T3 | 2 |
| 5 | T3 | 3 |
I need to produce a summary query that produces a single row for each user, with the first several teams (by TeamID) assigned sitting in separate columns. Like:
Query:
| UserID | Name | Team1 | Team2 |
| 1 | Joe | T1 | T2 |
| 2 | Fred | T2 | T3 |
| 3 | Bob | T3 | Null |
I can get the Team1 column using max() from a sub select query, but I’m having a complete mental block on how to achieve Team2, Team3, etc. (Yes, I know that if there are more teams assigned to a user than I create columns the query will lose that information: that isn’t a concern).
Edit: To clarify, the number of columns in the query will be fixed (in the actual query, there will always be 7). If there are less teams than columns the additional columns should be Null (as in example). If there are more teams than columns, only the first 7 teams will be shown in this summary.
Edit 2 – Possible solution which doesn’t work…:
I tried…
SELECT UserTable.ID As UID, UserTable.Name,
(SELECT TOP 1 TeamID FROM TeamTable WHERE UserTable.ID = TeamTable.UserID
ORDER BY TeamID) As Team1
FROM UserTable
… which works fine. Unfortunately…
SELECT UserTable.ID As UID, UserTable.Name,
(SELECT TOP 1 TeamID FROM TeamTable WHERE UserTable.ID = TeamTable.UserID
ORDER BY TeamID) As Team1,
(SELECT TOP 1 TeamID FROM TeamTable WHERE UserTable.ID = TeamTable.UserID
AND TeamID <> Team1 ORDER BY TeamID) As Team2
FROM UserTable
… throws up a parameter box for Team1. An ideas on how to skip the first/second/etc… values from an jet query?
First, you need a query to assign a number from 1 to N to the teams associated to a user:
Let’s call this query TeamList.
Now, you can use this query in the main query, by calling it 7 times, each time filtering a different position:
You could assemble all this in a single query, but it’s more practical to define the TeamList query and calling it multiple times.
Also note that this way the numbering is based on the order of TeamID. You can choose another order by changing the TeamList query, but the field you choose must have different unique values for each Team (or the <= comparison will generate wrong numbers).
Obviously, with a big number of rows performance would be terrible, but for a few hundreds it could be acceptable. You have to try.