日期:2014-05-17  浏览次数:20488 次

父子结构的表输出问题
有3个表
表一  主表 
   AID UserName
   1   a
   2   b

表二  副表  
   BID LevelName 
   1    aa
   2    bb
   3    aaa
   4    bbbb
   5    ccccc

表三  关系表 
   ID  AID  BID 
   1   1    1
   2   1    2
   3   2    3
   4   2    4
   5   2    5

现在 一个UserName 有多个关联多个LevelName  

怎么在一行记录中输出呢
例如
AID UserName  LevelName  
1   a         aa,bb
2   b         aaa,bbbb,ccccc

------解决方案--------------------

if object_id('Tempdb..#A') is not null drop table #A
if object_id('Tempdb..#B') is not null drop table #B
if object_id('Tempdb..#C') is not null drop table #C

--临时表A
create table #A
(
[AID] int identity(1,1) not null,
[UserName] nvarchar(10) null
)
 --临时表B
create table #B
(
[BID] int identity(1,1) not null,
[LevelName] nvarchar(10) null
)
--临时表C
create table #C
(
id int identity(1,1) not null,
[AID] int null,
[BID] int null
)
-----------添加测试数据---------
Insert into #A
 select 'a' union all
 select 'b'

Insert into #B
 select 'aa' union all
 select 'bb' union all
 select 'aaa' union all
 select 'bbbb' union all