我的Microsoft SQL服务器中有以下表格。我想将行转换为列。
我的问题是我不知道前面的结果,可能有超过3行 在结果中。
当前表格
ID - Function - Result - MasterKey
1 - 100 - 31 - 7
1 - 125 - 34 - 7
1 - 138 - 39 - 7
. - . - . - .
. - . - . - .
期望的结果
MasterKey - Function1 - Result1 - Function2 - Result2 - Function3 - Result3 - ...
7 - 100 - 31 - 125 - 34 - 138 - 39 - ...
我怎样才能实现它? 提前谢谢。
答案 0 :(得分:1)
如果您有未知数量的函数/结果,则需要动态创建SQL:
DECLARE @SQL NVARCHAR(MAX) = '';
SET @SQL = 'SELECT MasterKey' +
( SELECT ', Function' + RowNum + ' = MAX(CASE WHEN RowNumber = ' + RowNum + ' THEN [Function] END)' +
', Result' + RowNum + ' = MAX(CASE WHEN RowNumber = ' + RowNum + ' THEN Result END)'
FROM ( SELECT DISTINCT
RowNum = CAST(ROW_NUMBER() OVER (PARTITION BY MasterKey
ORDER BY [Function])
AS VARCHAR(10))
FROM T
) t
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)') +
' FROM (SELECT MasterKey, [Function], Result, RowNumber = ROW_NUMBER() OVER (PARTITION BY MasterKey ORDER BY [Function]) FROM T) AS T GROUP BY MasterKey';
EXECUTE sp_executesql @sql;
<强> Example on SQL Fiddle 强>