如何将多列转换为行号的单行?

时间:2016-09-29 14:14:28

标签: sql sql-server sql-server-2012 pivot cross-apply

我试图找出一种转换方式 [Column1],[Column2],[Column3],[Column4],[Column5]成单列[Type]。我也希望它有行号。这是我希望它看起来如何的一个例子。那么,如果我只想要列数据输出怎么办?像Column1和Column2一样,它们都有值,但是第3,4和5列都没有。在这种情况下,我只想在结果集上显示1和2。

现在:

[ID1]-[Column1],[Column2],[Column3],[Column4],[Column5]

[ID2]-[Column1],[Column2],[Column3],[Column4],[Column5]

欲望:

[ID1]-[Column1],[Row1]

[ID1]-[Column2],[Row2]

[ID1]-[Column3],[Row3]

[ID1]-[Column4],[Row4]

[ID1]-[Column5],[Row5]

[ID2]-[Column1],[Row1]

[ID2]-[Column2],[Row2]

Etc......

谢谢!

3 个答案:

答案 0 :(得分:0)

尝试这样的事情,但这可能不是可靠的解决方案,但首先要完成工作

SELECT Col,Row_NUMBER() OVER(ORDER BY [ID]) RowNo 
FROM (

         SELECT [ID],CAST([ID] AS VARCHAR(30))+'-'+[COLUMN1] as Col
         FROM TableName
         UNION ALL
         SELECT [ID],CAST([ID] AS VARCHAR(30))+'-'+[COLUMN2] as Col
         FROM TableName   
         UNION ALL
         SELECT [ID],CAST([ID] AS VARCHAR(30))+'-'+[COLUMN3] as Col
         FROM TableName
         ...Like wise for other columns

)M
ORDER BY [ID]

答案 1 :(得分:0)

通过使用Cross / Outer apply和Table Value Constructors来解析表格的一种方法。

--sample data
WITH cte AS (
    SELECT  *
    FROM    (VALUES (1, 'col1', 'col2', 'col3', 'col4', 'col5'),
                    (2, 'col1', 'col2', 'col3', 'col4', 'col5')) 
    t(id, column1,column2,column3,column4,column5) 
)
--query
SELECT  cte.id, 
        t.* 
FROM    cte 
OUTER APPLY (VALUES(column1, 1),(column2, 2),(column3, 3),(column4, 4),(column5, 5)) t([type],[rownum])

答案 2 :(得分:0)

您可以使用UNPIVOT将列反转为行:

;WITH YourTable AS (
SELECT *
FROM (VALUES
('ID1','Column11','Column12','Column13','Column14','Column15'),
('ID2','Column21','Column22','Column23','Column24','Column25')
) as t([ID],[Column1],[Column2],[Column3],[Column4],[Column5])
)

SELECT *
FROM (
    SELECT  [Column1] as [Row1],
            [Column2] as [Row2],
            [Column3] as [Row3],
            [Column4] as [Row4],
            [Column5] as [Row5],
            [ID]
    FROM YourTable
) t
UNPIVOT (
    [Type] FOR [Column] IN ([Row1],[Row2],[Row3],[Row4],[Row5])
) as unp

输出:

ID  Type        Column
ID1 Column11    Row1
ID1 Column12    Row2
ID1 Column13    Row3
ID1 Column14    Row4
ID1 Column15    Row5
ID2 Column21    Row1
ID2 Column22    Row2
ID2 Column23    Row3
ID2 Column24    Row4
ID2 Column25    Row5