Pivoting a table with predefined headers [closed]

北战南征 提交于 2020-01-07 03:18:07

问题


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:


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.



来源:https://stackoverflow.com/questions/43536461/pivoting-a-table-with-predefined-headers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!