日期:2014-05-17 浏览次数:20664 次
create table #table1 (yid int, yname nvarchar(10))
insert #table1
select 1 ,'张三' union all
select 2 ,'李四'
create table #table2 (cyid int , cynameid int)
insert #table2
select 1 , 22 union all
select 1 , 12 union all
select 2 , 22 union all
select 2 , 33
create table #table3 (sid int, sname nvarchar(10))
insert #table3
select 22 ,'北京' union all
select 33 ,'天津' union all
select 12 ,'上海'
--查询
with temp as
(
select t2.cyid,t3.sname from #table2 t2 left join #table3 t3 on t2.cynameid=t3.sid
)
select t1.yname,tt.sname from #table1 t1 left join
(
SELECT cyid,
STUFF((SELECT ','+ sname
FROM temp
WHERE cyid = t.cyid
FOR XML PATH('')),1,1,'') AS sname
FROM temp t GROUP BY cyid
)
tt on t1.yid=tt.cyid