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

sql合并列问题
A表字段
id name
1  张三
2  李四
B表字段
id   aid name
123  1   heihei
234  1    what
345  2    lisi
456  2    ii
567  2    li
查询效果  

A.id  A.name  B.name
1     张三    heihei,what
2     李四    lisi,ii,li

这个如何实现啊
只有25分,唉!
SQL

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

create table A表
(id int, name varchar(10))

insert into A表
select 1, '张三' union all
select 2, '李四'

create table B表
(id int, aid int, name varchar(10))

insert into B表
select 123, 1, 'heihei' union all
select 234, 1, 'what' union all
select 345, 2, 'lisi' union all
select 456, 2, 'ii' union all
select 567, 2, 'li'


select a.id,
       a.name,
       stuff((select ','+b.name from B表 b 
              where b.aid=a.id for xml path('')),1,1,'') 'name'
from A表 a

/*
id          name       name
----------- ---------- -----------------
1           张三         heihei,what
2           李四         lisi,ii,li

(2 row(s) affected)
*/