MS Access 2007:使用SQL将行转置为列

时间:2010-11-20 19:28:35

标签: sql ms-access-2007 transform

SQL新手在这里。我有以下表格设置(我对格式不佳的道歉):

周期ID .... UBCI .... chemo_cycle .... csf .... rsn_no_csf
57 ............. 18001 ... 1 ......................ññ.......
58 ............. 18001 ... 2 ......................ñ.... ... N
59 ............. 22002 ... 1 ......................ÿ ........空

我想将其转换为以下格式:

UBCI .... chemo_cycle1 .... chemo_cycle2 .... csf1 .... csf2 .... rsn_no_csf1 .... rsn_no_csf2
18001 ... 1 ....... .................. 2 .........................ñ..... ... N ........ň.....................ň
22002 ...... 1 ...... ...................空......................ÿ....... .NULL .....空..................空

每个UBCI最多可以有26个chemo_cycles。我尝试了其他一些建议,但对SQL不够熟悉,可以找出一些更精细的细节。再次,为格式化道歉。任何帮助将不胜感激。

谢谢!

-Omar

1 个答案:

答案 0 :(得分:1)

我可以在Access中方便地看到这样做的唯一方法是进行四次查询。我不认为你可以使用交叉表查询作为子查询,所以:

查询1:cc

TRANSFORM First(TableQ.chemo_cycle) AS FirstOfchemo_cycle
SELECT TableQ.UBCI
FROM TableQ
GROUP BY TableQ.UBCI
PIVOT "CC " & [chemo_cycle];

查询2:csf

TRANSFORM First(TableQ.csf) AS FirstOfcsf
SELECT TableQ.UBCI
FROM TableQ
GROUP BY TableQ.UBCI
PIVOT "csf " & [chemo_cycle];

查询3:rsn

TRANSFORM First(TableQ.rsn_no_csf) AS FirstOfrsn_no_csf
SELECT TableQ.UBCI
FROM TableQ
GROUP BY TableQ.UBCI
PIVOT "rsn " & [chemo_cycle];

最终查询: 列[cc 1]至[cc 26]将显示在设计窗口中,并且可以添加,此处它们由< ...>

表示
SELECT CC.UBCI, 
       CC.[CC 1], 
       CC.[CC 2], 
       <...>
       csf.[csf 1], 
       csf.[csf 2], 
       <...>
       rsn.[rsn 1], 
       rsn.[rsn 2]
       <...>
FROM (CC INNER JOIN csf 
ON CC.UBCI = csf.UBCI) 
INNER JOIN rsn 
ON csf.UBCI = rsn.UBCI;