--示例--示例数据 create table tb(借书证号 varchar(10),姓名 varchar(10),借书 varchar(10)) insert tb select '0001','张三','《红楼梦》' union all select '0001','张三','《西游记》' union all select '0001','张三','《市 话》' union all select '0002','李四','《高数》' union all select '0002','李四','《物理》' go--查询处理 select gid=0,* into #t from tb order by 借书证号 declare @i int,@s varchar(8000) update #t set @i=case @s when 借书证号 then @i+1 else 1 end ,gid=@i,@s=借书证号 select @s='',@i=max(gid) from #t while @i>0 select @s=',[借书'+cast(@i as varchar)+']=max(case gid when '+cast(@i as varchar)+' then 借书 else '''' end)'+@s ,@i=@i-1 exec('select 借书证号'+@s+' from #t group by 借书证号') drop table #t go--删除测试 drop table tb/*--测试结果借书证号 借书1 借书2 借书3 ---------- ---------- ---------- ---------- 0001 《红楼梦》 《西游记》 《市 话》 0002 《高数》 《物理》 --*/
1)循环借书证号
2)根据借书证号在循环图书
--示例--示例数据
create table tb(借书证号 varchar(10),姓名 varchar(10),借书 varchar(10))
insert tb select '0001','张三','《红楼梦》'
union all select '0001','张三','《西游记》'
union all select '0001','张三','《市 话》'
union all select '0002','李四','《高数》'
union all select '0002','李四','《物理》'
go--查询处理
select gid=0,* into #t from tb order by 借书证号
declare @i int,@s varchar(8000)
update #t set @i=case @s when 借书证号 then @i+1 else 1 end
,gid=@i,@s=借书证号
select @s='',@i=max(gid) from #t
while @i>0
select @s=',[借书'+cast(@i as varchar)+']=max(case gid when '+cast(@i as varchar)+' then 借书 else '''' end)'+@s
,@i=@i-1
exec('select 借书证号'+@s+' from #t group by 借书证号')
drop table #t
go--删除测试
drop table tb/*--测试结果借书证号 借书1 借书2 借书3
---------- ---------- ---------- ----------
0001 《红楼梦》 《西游记》 《市 话》
0002 《高数》 《物理》
--*/