在访问中将垂直表格设置为水平

时间:2014-02-07 09:31:51

标签: sql ms-access access-vba

我有这张桌子:

+----+------+
| ID | NAME |
+----+------+
|  1 | A    |
|  1 | B    |
|  1 | C    |
|  2 | A    |
|  2 | P    |
|  2 | D    |
|  2 | X    |
|  3 | F    |
|  3 | 45   |
+----+------+

我希望将其转换为此。 (该ID将是唯一的,并且相同ID的每个重复ID的名称将添加到新字段中。

+----+------+-------+-------+-------+
| ID | NAME | Name1 | Name2 | Name3 |
+----+------+-------+-------+-------+
|  1 | A    | B     | C     |       |
|  2 | A    | P     | D     | X     |
|  3 | F    | 45    |       |       |
+----+------+-------+-------+-------+

在Access中有一种快速的方法吗? VBA代码没问题。我试过Pivot和转置(在Excel中)都不起作用,或者没有给我想要的结果。像(第一行Name3)这样的空单元格没问题。任何建议,链接或代码片段都非常感谢!

1 个答案:

答案 0 :(得分:2)

这会给你类似的东西:

TRANSFORM FIRST([Name]) AS FirstOfName
SELECT ID
FROM
    (
        SELECT t1.ID, t1.Name, 'Name' & Format(COUNT(*),"000") AS NewName
        FROM
            YourTable AS t1
            INNER JOIN
            YourTable AS t2
                ON t1.ID = t2.ID
                    AND t1.Name >= t2.Name
        GROUP BY t1.ID, t1.Name
    )
GROUP BY ID
PIVOT NewName

对于[YourTable]中的测试数据

ID  Name
--  ----
 1  A   
 1  B   
 1  C   
 2  A   
 2  P   
 2  D   
 2  X   
 3  F   
 3  45  

它返回

ID  Name001  Name002  Name003  Name004
--  -------  -------  -------  -------
 1  A        B        C           
 2  A        D        P        X    
 3  45       F