我希望我能清楚地理解你。虽然我仍然使用 PIVOT,但在这里,我假设我也不知道学生证。
create table Student (
ClassID INT
, StudentID INT
)
INSERT INTO Student (ClassID, StudentID) VALUES
(1,10)
, (1,11)
, (2,12)
, (2,10)
, (3,13)
select
'Student' + CONVERT(NVARCHAR(150),ROW_NUMBER () OVER (PARTITION BY ClassID ORDER BY StudentID)) AS StudentNo
, *
into #tmpStud
from Student
declare @distinct nvarchar(max) = ''
/*
option a : flexible to the number of students
*/
--set @distinct = (select distinct '[' + StudentNo + '],' as [text()] from #tmpStud for xml path(''))
--set @distinct = SUBSTRING(@distinct, 0, LEN(@distinct))
/*
option b : max of 32 student
*/
declare @max int = 33
, @loop int = 1
while (@loop < @max)
begin
if(@loop = 1) begin
set @distinct = @distinct + '[Student' + Convert(nvarchar(20),@loop) + ']'
set @loop = @loop + 1
end
else begin
set @distinct = @distinct + ',[Student' + Convert(nvarchar(20),@loop) + ']'
set @loop = @loop + 1
end
end
exec ('
select
*
from (
select
ClassID
, StudentNo
, StudentID
FROM #tmpStud
) AS s PIVOT
(
MAX(StudentID)
FOR StudentNo IN (' + @distinct + ')
) AS pvt
')
drop table #tmpStud
编辑:一旦您创建了学生表,请运行以下代码:
select
'Student' + CONVERT(NVARCHAR(150),ROW_NUMBER () OVER (PARTITION BY ClassID ORDER BY StudentID)) AS StudentNo
, *
into #tmpStud
from Student
declare @distinct nvarchar(max) = ''
/*
option a : flexible to the number of students
*/
set @distinct = (select distinct '[' + StudentNo + '],' as [text()] from #tmpStud for xml path(''))
set @distinct = SUBSTRING(@distinct, 0, LEN(@distinct))
exec ('
select
*
from (
select
ClassID
, StudentNo
, StudentID
FROM #tmpStud
) AS s PIVOT
(
MAX(StudentID)
FOR StudentNo IN (' + @distinct + ')
) AS pvt
')
drop table #tmpStud
编辑:假设您需要一个静态的 32 名学生 @ max..使用下面的脚本。
select
'Student' + CONVERT(NVARCHAR(150),ROW_NUMBER () OVER (PARTITION BY ClassID ORDER BY StudentID)) AS StudentNo
, *
into #tmpStud
from Student
declare @distinct nvarchar(max) = ''
/*
option b : static max of 32 student
*/
declare @max int = 33
, @loop int = 1
while (@loop < @max)
begin
if(@loop = 1) begin
set @distinct = @distinct + '[Student' + Convert(nvarchar(20),@loop) + ']'
set @loop = @loop + 1
end
else begin
set @distinct = @distinct + ',[Student' + Convert(nvarchar(20),@loop) + ']'
set @loop = @loop + 1
end
end
exec ('
select
*
from (
select
ClassID
, StudentNo
, StudentID
FROM #tmpStud
) AS s PIVOT
(
MAX(StudentID)
FOR StudentNo IN (' + @distinct + ')
) AS pvt
')
drop table #tmpStud