将单列转换为单行

Convert single column to single row

我有一个 table 单列,如下所示:

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

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

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

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

数据透视表查询:

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

您可以按如下方式进行数据透视:

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