--建立测试环境
Create Table 表
(學號 Int,
科目 Nvarchar(10),
成績 Int)
Insert 表 Values(1, N'語文', 95)
Insert 表 Values(1, N'數學', 92)
Insert 表 Values(1, N'英語', 90)
Insert 表 Values(1, N'歷史', 79)
Insert 表 Values(1, N'物理', 80)
Insert 表 Values(1, N'政治', 78)
Insert 表 Values(1, N'化學', 65)
Insert 表 Values(1, N'體育', 75)
GO
--测试
Declare @s Nvarchar(2000)
Set @s=''
Select TOP 5 @S=@S+',['+科目+N']=sum(case 科目 when N'''+科目+N''' then 成績 else 0 end)'
from 表
EXEC(N'Select 學號'+@s+N' from 表 group by 學號')
--删除测试环境
Drop Table 表
--结果
/*
學號 語文 數學 英語 歷史 物理
1 95 92 90 79 80
*/
Create Table 表
(學號 Int,
科目 Nvarchar(10),
成績 Int)
Insert 表 Values(1, N'語文', 95)
Insert 表 Values(1, N'數學', 92)
Insert 表 Values(1, N'英語', 90)
Insert 表 Values(1, N'歷史', 79)
Insert 表 Values(1, N'物理', 80)
Insert 表 Values(1, N'政治', 78)
Insert 表 Values(1, N'化學', 65)
Insert 表 Values(1, N'體育', 75)
GO
--测试
Declare @s Nvarchar(2000)
Set @s=''
Select TOP 5 @S=@S+',['+科目+N']=sum(case 科目 when N'''+科目+N''' then 成績 else 0 end)'
from 表
EXEC(N'Select 學號'+@s+N' from 表 group by 學號')
--删除测试环境
Drop Table 表
--结果
/*
學號 語文 數學 英語 歷史 物理
1 95 92 90 79 80
*/
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货