温馨提示×

sqlserver行转列怎么实现

小亿
86
2024-03-01 09:28:15
栏目: 云计算

在 SQL Server 中,可以使用 PIVOT 操作符将行转列。以下是一个示例:

假设有一个名为 StudentScore 的表,包含以下数据:

StudentID Subject Score
1 Math 80
1 English 75
2 Math 90
2 English 85

要将上面的数据行转列,可以使用以下 SQL 查询:

SELECT StudentID, [Math], [English]
FROM 
(SELECT StudentID, Subject, Score
 FROM StudentScore) AS SourceTable
PIVOT
(
 MAX(Score)
 FOR Subject IN ([Math], [English])
) AS PivotTable;

执行上述查询后,将得到以下结果:

StudentID Math English
1 80 75
2 90 85

这样就实现了将行转列的功能。

0