将单列转换为单行

时间:2017-07-18 14:29:27

标签: sql-server tsql unpivot

我有一个包含单列的表,如下所示:

+-------------+
|(Column Name)|
+-------------+
|Data1        |
+-------------+
|Data2        |
+-------------+
|Data3        |
+-------------+
|Data4        |
+-------------+
|Data5        |
+-------------+

我想做的事情似乎很简单,但我无法在任何地方找到任何例子。我想要的是将上面的列转换为单行,如下所示:

+-------+-------+-------+-------+-------+
| (Col1)| (Col2)| (Col3)| (Col4)| (Col5)|
+-------+-------+-------+-------+-------+
| Data1 | Data2 | Data3 | Data4 | Data5 |
+-------+-------+-------+-------+-------+

我确信这是一项非常简单的任务,但我对使用数据库非常陌生。我感谢任何帮助。

2 个答案:

答案 0 :(得分:6)

你可以按照以下方式进行调整:

Select * from (
    Select colname, RowN = Row_Number() over (order by colname) from #cols
    ) a
    pivot (max(colname) for RowN in ([1],[2],[3],[4],[5])) p

用于动态列列表

Declare @cols nvarchar(max)
Declare @query nvarchar(max)

Select @cols = stuff((select ','+QuoteName(Row_Number() over (Order by (Select NULL))) from #cols for xml path('')),1,1,'')
Select @query = ' Select * from (
    Select colname, RowN = Row_Number() over (order by colname) from #cols
    ) a
    pivot (max(colname) for RowN in (' + @cols + ')) p '

Exec sp_executesql @query

答案 1 :(得分:1)

透视查询:

CREATE TABLE Sales ([Month] VARCHAR(20) ,SaleAmount INT)

INSERT INTO Sales VALUES ('January', 100)
INSERT INTO Sales VALUES ('February', 200)
INSERT INTO Sales VALUES ('March', 300)

SELECT * FROM SALES

示例:

SELECT  [January]
      , [February]
      , [March]
FROM    ( SELECT    [Month]
                  , SaleAmount
          FROM      Sales
        ) p PIVOT ( SUM(SaleAmount)
                    FOR [Month] 
                      IN ([January],[February],[March])
                  ) AS pvt