表s
sindex  sname
s1        张三
s2        李四
表t
tindex   tname
t1       他是谁
t2       不认识
表sc
sindex   tindex
s1       t2
s1       t1
s2       t1现在想的到一个类似于如下结构的结果
sindex        sname        tindexs      tnames
s1            张三         t1,t2                              他是谁,不认识
s2            李四         t1                                  他是谁直接用sql能实现么咋弄啊,注意所有的index是变动的,不会是固定t1 t2 s1 s2这样的
谢谢

解决方案 »

  1.   

    ;
    WITH    huang
              AS ( SELECT   s.sindex ,
                            sname ,
                            t.tindex ,
                            t.tname
                   FROM     S
                            INNER JOIN sc ON s.sindex = sc.sindex
                            INNER JOIN t ON sc.tindex = t.tindex
                 )
        SELECT  a.sindex ,
                a.sname ,
                STUFF(( SELECT  ',' + tindex
                        FROM    huang b
                        WHERE   b.sindex = a.sindex
                                AND b.sname = a.sname
                      FOR
                        XML PATH('')
                      ), 1, 1, '') 'tindexs' ,
                STUFF(( SELECT  ',' + tname
                        FROM    huang b
                        WHERE   b.sindex = a.sindex
                                AND b.sname = a.sname
                      FOR
                        XML PATH('')
                      ), 1, 1, '') 'tnames'
        FROM    huang a
        GROUP BY a.sindex ,
                a.sname
      

  2.   

    当然查询也可以在一个视图基础上
    将表s 表t 表sc合成一个视图
    sindex    sname    tindex    tname
    s1        张三     t1        他是谁
    s1        张三     t2        不知道
    s2        李四     t1        他是谁最终要这样个结果就行了
    sindex        sname        tindexs      tnames
    s1            张三         t1,t2       他是谁,不认识
    s2            李四         t1           他是谁
      

  3.   

    with s(sindex,sname)
     as(
     select 's1','张三' union all
     select 's2','李四'),
     t(tindex,tname)
     as(
     select 't1','他是谁' union all
     select 't2','不认识'),
     sc(sindex,tindex)
     as(
     select 's1','t2' union all
     select 's1','t1' union all
     select 's2','t1')
     select sindex,sname,stuff((select ','+tindex from sc sc2 where sc2.sindex=s1.sindex  order by tindex for xml path('')),1,1,'')tindexs,
     stuff((select ','+tname from t t2,sc sc2 where t2.tindex=sc2.tindex and sc2.sindex=s1.sindex for xml path('')),1,1,'')tnames from s s1