0

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

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

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 

结果

我正在尝试使其成为动态查询,下面是我目前正在尝试的代码片段

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;

这仍然需要一些调整。感谢你的帮助..

4

1 回答 1

1

您可以使用如下所示的数据透视查询:

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

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

动态枢轴链接 1

动态枢轴链接 2

动态枢轴链接 3

于 2012-06-09T10:42:18.840 回答