34,575
社区成员
发帖
与我相关
我的任务
分享
use Tempdb
go
--> --> 中国风(Roy)生成測試數據
if not object_id(N'Tempdb..#T1') is null
drop table #T1
Go
Create table #T1([姓名] nvarchar(102),[期数] bigint,[科目] nvarchar(104),[分数] bigint)
Insert #T1
select N'张三',1,N'中级考试',80 union all
select N'张三',2,N'中级考试',92 union all
select N'张三',3,N'中级考试',95 union all
select N'李四',1,N'中级考试',65 union all
select N'李四',2,N'中级考试',72 union all
select N'李四',4,N'中级考试',99 union all
select N'王五',1,N'中级考试',90 union all
select N'王五',2,N'中级考试',86 union all
select N'王五',3,N'中级考试',55 union all
select N'王五',4,N'中级考试',50
GO
DECLARE @Sql NVARCHAR(4000)='select [姓名]'
Select @Sql+=',max(case when [期数]='+RTRIM([期数])+' THEN [科目] ELSE '''' END) AS 科目'+RTRIM([期数])+',max(case when [期数]='+RTRIM([期数])+' then [分数] end) AS 期数'+RTRIM([期数]) from #T1 GROUP BY [期数]
SET @Sql+=' from #T1 group by [姓名]'
EXEC (@Sql)
/*
姓名 科目1 期数1 科目2 期数2 科目3 期数3 科目4 期数4
李四 中级考试 65 中级考试 72 NULL 中级考试 99
王五 中级考试 90 中级考试 86 中级考试 55 中级考试 50
张三 中级考试 80 中级考试 92 中级考试 95 NULL
*/