How to simulate UNPIVOT in Access?

女生的网名这么多〃 提交于 2019-11-26 13:49:09

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

Unfortunately there is no easy way to do this with access. You can do this by using a UNION to get each value

SELECT ID, A, B, C, [Key 1] As key
FROM Table
WHERE [Key 1] = 3

UNION ALL

SELECT ID, A, B, C, [Key 1] As key
FROM Table
WHERE [Key 1] = 57

UNION ALL

SELECT ID, A, B, C, [Key 2] As key
FROM Table
WHERE [Key 2] = 199

UNION ALL

SELECT ID, A, B, C, [Key 2] As key
FROM Table
WHERE [Key 2] = 234

UNION ALL

SELECT ID, A, B, C, [Key 3] As key
FROM Table
WHERE [Key 3] = 452
Vinicius Sousa
  1. You can create a auxiliary table with all column names as values (can use excel copy the first row of your table to excel > paste special > transpose)

  2. Create in your table a auto increment column and index this column

  3. Create a new cross join query like the following

SELECT ID, A, B, C
       , AUX_TABLE.KEY_FIELD
       , DLookUp("[" & [AUX_TABLE].[KEY_FIELD] & "]","TABLE","[ID] = " & [TABLE].[ID]) AS KEY_VALUE
FROM TABLE, AUX_TABLE;

Downside would be you have to maintain AUX_TABLE to keep that working. But if this is a one-time-thing this might be the way to go.

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