将具有多行的单列转换为具有多列的单行

时间:2012-06-09 09:41:37

标签: sql sql-server-2008 tsql

我需要将列数据转换为具有多列的单行

示例 - 我创建了一个临时表来加载列

的数据
CREATE TABLE TestC (Comments Char(100), Row_Count [int] IDENTITY(1,1))

INSERT INTO TestC VALUES('A'),('B'),('C'),('D')

Select Min( Case When Row_Count = 1 Then Comments End ) As Comments 
, Min( Case When Row_Count = 2 Then Comments End ) As Comments 
, Min( Case When Row_Count = 3 Then Comments End ) As Comments 
, Min( Case When Row_Count = 4 Then Comments End ) As Comments 
, Min( Case When Row_Count = 5 Then Comments End ) As Comments 
, Min( Case When Row_Count = 6 Then Comments End ) AS Comments 
, Min( Case When Row_Count = 7 Then Comments End ) AS Comments 
FROM TestC 

Result

我正在尝试进行动态查询,下面是我目前正在尝试的代码段

DECLARE @sql AS NVARCHAR (MAX);
SELECT   @sql =  ' SELECT Min (CASE WHEN [Row_Count] =' + CAST ([Row_Count] AS CHAR(5)) + 
' THEN [Comments] END) AS Comments'
FROM     [dbo].[TestC];
SET @sql = @sql + N' FROM  [dbo].[TestC] ';
PRINT @sql
EXECUTE sp_executesql @sql;

这还需要一些调整。感谢您的帮助..

1 个答案:

答案 0 :(得分:1)

您可以使用透视查询,如下所示:

SELECT Pvt.*
FROM (
    SELECT *
    FROM TestC
    )AS P
PIVOT (MIN(Comments) FOR Row_Count IN ([1],[2],[3],[4],[5],[6],[7]))Pvt

编辑: 您可以在下面看到链接:

Dynamic Pivot Link 1

Dynamic Pivot Link 2

Dynamic Pivot Link 3