简体   繁体   中英

SQL Query for Pivoting data in MS-Access

I have a table with three fields: ticketNumber, attendee and tableNumber.

eg

ticketNumber | attendee | tableNumber
------------ | -------- | -----------
     A1      | alex     |     3  
     A2      | bret     |     2  
     A3      | chip     |     1  
     A4      | dale     |     2  
     A5      | eric     |     2  
     A6      | finn     |     3

I'd like to generate a table with each tableNumber as a field and the list of names sitting at that tableNumber.

1  |  2   | 3
-----|------|-----
chip | bret | alex 
     | dale | finn
     | eric |

The query I've been working on is:

transform attendee
select attendee
from registration
group by tableNumber, name
pivot tableNumber

This gives me:

attendee |  1   |  2   |  3 
---------|------|------|----- 
chip     | chip |      | 
bret     |      | bret |
dale     |      | dale |
eric     |      | eric |
alex     |      |      | alex
finn     |      |      | finn

I know how to get the table I require using PivotTableView but I'd like to know how to do it with a query so that I can use it in a code I'm working on. I'm unsure of how I can write this query without having to select a field (in my case, select attendee). Also is it possible to generate the table without the empty cells?

Thank you :)

The table needs a unique identifier field that will properly sort and I don't think the ticketNumber can be relied on for that. An autonumber should serve. Then try:

TRANSFORM First(Table1.attendee) AS FirstOfattendee SELECT DCount("*","Table1","tableNumber=" & [tableNumber] & " AND ID<" & [ID])+1 AS RowSeq FROM Table1 GROUP BY DCount("*","Table1","tableNumber=" & [tableNumber] & " AND ID<" & [ID])+1 PIVOT Table1.tableNumber;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM