0

I asked this question a few months back but now I'm working out of MS-Access and I'm unsure how to proceed. I have a query that lists the bldid, unitid, and resident id in separate columns. I'd like to modify the query output in Microsoft Access so that each resident that shares a building / unit shows as a new column on the same row as shown below. But since I'm limited to MS Access I can't seem to use with, cte, or rownumber. I'm at a loss as to how to do this so any help would be appreciated.

Query1

BldID UnitID ResidentID
1 201 John Smith
1 201 Jane Doe
1 202 Daniel Jones
1 202 Mark Garcia
2 201 Maria Lee
2 201 Paul Williams
2 201 Mike Jones

Desired Output from edited Query

BldID UnitID Res1 Res2 Res3
1 201 John Smith Jane Doe
1 202 Daniel Jones Mark Garcia
2 201 Maria Lee Paul Williams Mike Jones
llOmni
  • 35
  • 4
  • Does this answer your question? [Pivot Query in MS Access](https://stackoverflow.com/questions/64400911/pivot-query-in-ms-access) – June7 May 26 '21 at 15:54

1 Answers1

0

You can use a Crosstab Query

TRANSFORM Max(Resident.ResidentID) AS MaxOfResidentID
SELECT Resident.BldID, Resident.UnitID
FROM Resident
GROUP BY Resident.BldID, Resident.UnitID
ORDER BY Resident.BldID, Resident.UnitID
PIVOT "Res" & (DCount("*",
               "Resident",
               "BldID=" & [BldID] & " AND UnitID=" & [UnitID] &
               " AND ResidentID<'" & [ResidentID] & "'") + 1);

If you need a constant number of columns (e.g. if you want to create an Access report), then you can add an In clause to this query (before the ;):

In ("Res1","Res2","Res3","Res4","Res5","Res6")

This always creates 6 columns with the same names.

The difficulty is to get the row number per BldID/UnitID group. This is achieved by

DCount(1,
       "Resident",
       "BldID=" & [BldID] & 
       " AND UnitID=" & [UnitID] &
       " AND ResidentID<'" & [ResidentID] & "'") + 1

where Resident is the name of your table or query. It counts residents having the same BldID and UnitID but having a smaller ResidentID. Adding 1 to this count yields the row number starting at 1. Then the string "Res" is prepended to build the column name.

Note that the residents are listed in alphabetical order form left to right.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
  • Thanks to your detailed example. I was able to get this working with only a few issues. I do have a question, if either BldID or UnitID were to be a short text field instead of a number field how would I adjust Dcount to handle that? – llOmni May 26 '21 at 17:58
  • In SQL strings are enclosed in single quotes. You would have to enclose both of them in single quotes as I did for `ResidentID` in the `DCount` function. `"BldID='" & [BldID] & "' AND UnitID='" & [UnitID] & "' AND ResidentID<'" & [ResidentID] & "'"` – Olivier Jacot-Descombes May 26 '21 at 18:00