将sql列值合并到字段名称中

时间:2018-03-17 16:29:36

标签: sql-server-2012

我想重新格式化表1,将“考试尝试#”连接到列ID,如表2所示:如果可能,使用sql查询编辑器。

SQL Server Table

Query output format preferred

1 个答案:

答案 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中完成,但使用宿主语言进行格式化会更简洁。