How to simulate UNPIVOT in Access?

Andreas Spindler picture Andreas Spindler · Aug 31, 2011 · Viewed 18.3k times · Source

UNPIVOT is available in MS SQL-Server 2005, but AFAIK not in MS Access 2010. How can it be implemented with on-board means? For example, I have a table

ID | A | B | C | Key 1 | Key 2 | Key 3
---------------------------------------
 1 | x | y | z |     3 |   199 |   452
 2 | x | y | z |    57 |   234 |   452

and want to have a table like

ID | A | B | C | Key
--------------------
 1 | x | y | z |   3
 2 | x | y | z |  57
 1 | x | y | z | 199
 2 | x | y | z | 234
 2 | x | y | z | 452

Key 452 is a special case. Currently I do the rotation in OLEDB/ATL C++. Although it is fast enough I'm still curious. What is the most efficient SQL statement for Access 2010 here?

Answer

HansUp picture HansUp · Aug 31, 2011

This query ...

SELECT ID, A, B, C, [Key 1] AS key_field
FROM tblUnpivotSource
UNION ALL
SELECT ID, A, B, C, [Key 2] AS key_field
FROM tblUnpivotSource
UNION ALL
SELECT ID, A, B, C, [Key 3] AS key_field
FROM tblUnpivotSource;

... returns this recordset (using your sample table values as tblUnpivotSource) ...

ID A B C key_field
-- - - - ---------
 1 x y z         3
 2 x y z        57
 1 x y z       199
 2 x y z       234
 1 x y z       452
 2 x y z       452