Pivoting a table with predefined headers [closed]

2019-09-18 15:46发布

ID | NAME | Description
A    A      Value1
A    A      Value2
B    B      Value1
C    C      Value1
C    C      Value2
C    C      Value3
D    D      Value1
D    D      Value2
D    D      Value3
D    D      Value4
D    D      Value5
D    D      Value6

I have this input, and i am trying to convert it into this.

ID | NAME | Desc1 | Desc2 | Desc3 | Desc4 | Desc5 | Desc6
A    A      Value1  Value2
B    B      Value1
C    C      Value1  Value2  Value3
D    D      Value1  Value2  Value3  Value4  Value5  Value6

I have tried doing pivot and transform. but not going anywhere.

transform max([Description])
select ID, [Description]
from TableName
Group ID
Pivot [Description]

Any help would be apprecaited.

1条回答
一纸荒年 Trace。
2楼-- · 2019-09-18 16:03

Name is a reserved word. Should not use reserved words as names for anything.

One approach uses DCount(). The table will need a unique identifier field - autonumber should serve for this. Build query:

SELECT Table1.ID, Table1.Name, Table1.Description, Table1.NumID, 
DCount("*","Table1","ID='" & [ID] & "' AND NumID<" & [NumID])+1 AS GrpNum
FROM Table1
ORDER BY Table1.ID, Table1.NumID;

Then use that query in CROSSTAB.

TRANSFORM First(Query3.Description) AS FirstOfDescription
SELECT Query3.ID, Query3.Name
FROM Query3
GROUP BY Query3.ID, Query3.Name
PIVOT Query3.GrpNum;

However, domain aggregate functions can perform slowly in query for very large dataset.

A VBA procedure could write records to a 'temp' table (table is permanent, data is temporary) in the pivoted structure. This code might execute faster than query using domain aggregate function for large datasets.

Text file could be imported into 'temp' table with autonumber field and then run the suggested queries.

查看更多
登录 后发表回答