使用PIVOT一個例子:
DECLARE @Students TABLE
(
name varchar(10),
grade char(1),
[subject] varchar(10)
);
INSERT INTO @Students VALUES ('JOHN', 'A', 'MATH');
INSERT INTO @Students VALUES ('JOHN', 'C', 'PHYSIC');
INSERT INTO @Students VALUES ('JENNY', 'B', 'PHYSIC');
INSERT INTO @Students VALUES ('JENNY', 'C', 'MATH');
INSERT INTO @Students VALUES ('KENNY', 'A', 'MATH');
INSERT INTO @Students VALUES ('KENNY', 'B', 'PHYSIC');
SELECT *
FROM @Students AS Students
PIVOT
(
MAX(Grade)
FOR [subject] IN ([MATH], [PHYSIC])
) AS StudentGrades
我相信PIVOT關係運算符將在這種情況下工作,雖然我沒有很多的經驗,實現它自己。 http://msdn.microsoft.com/en-us/library/ms177410.aspx – hqrsie