1.现有一张表
姓名 学科 成绩
张三 语文 80
张三 数学 60
张三 英语 70
李四 语文 40
李四 数学 80
李四 英语 60
王五 语文 64
王五 数学 79
王五 英语 69
要求:写一个存储过程
输出以下结果:
张三 语文(80),数学(60),英语(70)
李四 语文(40),数学(80),英语(60)
王五 语文(64),数学(79),英语(69)
------解决方案--------------------
- SQL code
if OBJECT_ID('tb')<>'' drop table tbcreate table tb (姓名 nvarchar(20), 学科 nvarchar(10) ,成绩 int)insert into tb select '张三','语文',80union allselect '张三','数学',60union allselect '张三','英语',70union allselect '李四','语文',40union allselect '李四','数学',80union allselect '李四','英语',60union allselect '王五','语文',64union allselect '王五','数学',79union allselect '王五','英语',69gocreate procedure ptempasbegin set nocount on ; select 姓名, '语文('+cast(sum(case 学科 when '语文' then 成绩 else 0 end) as nvarchar(10))+')' as 语文, '数学('+cast(sum(case 学科 when '数学' then 成绩 else 0 end) as nvarchar(10))+')' as 数学 , '数学('+cast(sum(case 学科 when '英语' then 成绩 else 0 end) as nvarchar(10))+')' as 英语 from tb group by 姓名endgoexec ptempgodrop procedure ptempdrop table tb go--(9 行受影响)--姓名 语文 数学 英语---------------------- ---------------- ---------------- ------------------李四 语文(40) 数学(80) 数学(60)--王五 语文(64) 数学(79) 数学(69)--张三 语文(80) 数学(60) 数学(7
------解决方案--------------------
- SQL code
create table tb (姓名 nvarchar(20), 学科 nvarchar(10) ,成绩 int)insert into tb select N'张三',N'语文',80union allselect N'张三',N'数学',60union allselect N'张三',N'英语',70union allselect N'李四',N'语文',40union allselect N'李四',N'数学',80union allselect N'李四',N'英语',60union allselect N'王五',N'语文',64union allselect N'王五',N'数学',79union allselect N'王五',N'英语',69goselect 姓名,信息=stuff((select ','+学科+'('+rtrim(成绩)+')' from tb where 姓名=a.姓名 for xml path('')),1,1,'')from tb a group by 姓名 /*姓名 信息-------------------- ----------------------------张三 语文(80),数学(60),英语(70)李四 语文(40),数学(80),英语(60)王五 语文(64),数学(79),英语(69)