将多列转换为行

时间:2011-10-31 18:32:07

标签: sql-server-2005 sql-server-2008 rows

我有一个包含以下列的遗留表。

Create Table test
( id varchar(50)
, code1 varchar(50)
, codeDesc1 varchar(50)
, code2 varchar(50)
, codeDesc2 varchar(50)
, code3 varchar(50)
, codeDesc3 varchar(50)
, code4 varchar(50)
, codeDesc4 varchar(50)
, code5 varchar(50)
, codeDesc5 varchar(50)
, code6 varchar(50)
, codeDesc6 varchar(50)
)

insert into test (id, code1, codeDesc1, code2, codeDesc2, code3, codeDesc3, code4, codeDesc4, code5, codeDesc5, code6, codeDesc6)
values ('1','100.1', 'first code','100.2', 'Second code','100.3', 'Third code','100.4', 'Fourth code','100.5', 'Fifth code','100.6', 'Sixth code')

insert into test (id, code1, codeDesc1, code2, codeDesc2, code3, codeDesc3, code4, codeDesc4, code5, codeDesc5, code6, codeDesc6)
values ('2','100.1', 'first code','100.2', 'Second code','100.3', 'Third code','100.4', 'Fourth code','100.5', 'Fifth code','100.6', 'Sixth code')

select * from test

返回如下:

id, code1, codeDesc1, code2, codeDesc2, code3, codeDesc3, code4, codeDesc4, code5, codeDesc5, code6, codeDesc6

1,100.1, first code,100.2, Second code,100.3, Third code,100.4, Fourth code,100.5, Fifth code,100.6, Sixth code

2,100.1, first code,100.2, Second code,100.3, Third code,100.4, Fourth code,100.5, Fifth code,100.6, Sixth code

但我想恢复数据,如下所示:

ID, Code, Description

1, 100.1, First Code
1, 100.2, Second Code
1, 100.3, Third Code
1, 100.4, Fourth Code
1, 100.5, Fifth Code
1, 100.6, Sixth Code
2, 100.1, First Code
2, 100.2, Second Code
2, 100.3, Third Code
2, 100.4, Fourth Code
2, 100.5, Fifth Code
2, 100.6, Sixth Code

有人可以帮我怎么做吗?

我尝试了UNPIVOT,但没有给我我想要的确切结果。这是我使用的查询,但需要调整以获得确切的结果,我发现困难的时间。

SELECT Id, FieldCode , FieldValue
    FROM 
    (
        SELECT  id, code1, codeDesc1, code2, codeDesc2, code3, codeDesc3, code4, codeDesc4, code5, codeDesc5, code6, codeDesc6
        FROM test
    ) MyTable
    UNPIVOT
    (FieldValue FOR FieldCode IN (code1, codeDesc1, code2, codeDesc2, code3, codeDesc3, code4, codeDesc4, code5, codeDesc5, code6, codeDesc6))AS MyUnPivot

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

没关系,找到了答案。感谢Mangal这个精彩的网站http://mangalpardeshi.blogspot.com/2009/04/unpivot-multiple-columns.html

这是我的查询解决了我的问题:我发布在这里,以便任何人看起来

SELECT Id, FieldCode, FieldValue
    FROM 
    (
        SELECT  id, code1, codeDesc1, code2, codeDesc2, code3, codeDesc3, code4, codeDesc4, code5, codeDesc5, code6, codeDesc6
        FROM test
    ) MyTable

    UNPIVOT
    (FieldCode FOR FieldCodes IN (code1, code2, code3, code4, code5, code6))AS CODE

    UNPIVOT
    (FieldValue FOR FieldValues IN (codeDesc1, codeDesc2, codeDesc3, codeDesc4, codeDesc5, codeDesc6))AS FieldValues

WHERE RIGHT(FieldCodes,1) =  RIGHT(FieldValues,1)

现在获得正确结果的技巧部分是在最后的WHERE子句中,这取决于您使用的列名。因此,在尝试使用它之前,请尝试理解代码。

另外,最好在初始查询中检查ISNULL,并返回原始列。因为一旦它处于UNPIVOT模式,你就没有改变来检查它并且可能会出现错误。

祝你好运!