答案 0 :(得分:0)
如果您提前知道有多少次尝试,可以使用PIVOT编写它:
SELECT
p.StudentID,
p.[1] AS ExamAttempt_1,
p.[2] AS ExamAttempt_2,
p.[3] AS ExamAttempt_3
FROM #Scores s
PIVOT (MIN(s.ExamScore) FOR s.ExamAttempt IN ([1], [2], [3])) p
;
该查询假定数据位于临时表#Scores中。
如果不这样做,可以使用动态SQL生成PIVOT。这有点棘手。
DECLARE @ValueList NVARCHAR(4000);
DECLARE @ColumnList NVARCHAR(4000);
WITH Attempts AS
(
SELECT DISTINCT
ExamAttempt,
CAST(ExamAttempt AS NVARCHAR(10)) AS AttemptStr
FROM #Scores s
)
, Pretty AS
(
SELECT ExamAttempt,
'[' + AttemptStr + ']' AS ValueStr,
'[' + AttemptStr + '] AS ExamScore_' + AttemptStr AS ColumnStr
FROM Attempts
)
SELECT
@ValueList = COALESCE(@ValueList + ', ', '') + ValueStr,
@ColumnList = COALESCE(@ColumnList + ', ', '') + ColumnStr
FROM Pretty
ORDER BY ExamAttempt ASC
;
DECLARE @Sql NVARCHAR(MAX) =
'SELECT StudentId, '
+ @ColumnList
+ ' FROM #Scores s PIVOT (MIN(ExamScore) '
+ ' FOR ExamAttempt IN ( '
+ @ValueList
+ ')) p'
;
EXEC sys.sp_executesql @Sql;
@Sql变量基本上保存了第一个代码片段中的文本,直到细节。
请注意,虽然这可以在SQL中完成,但使用宿主语言进行格式化会更简洁。