首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

不知咋描述,算是行列转换?该如何处理

2013-01-26 
不知咋描述,算是行列转换?表ssindexsnames1张三s2李四表ttindextnamet1他是谁t2不认识表scsindextindexs1t

不知咋描述,算是行列转换?
表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这样的
谢谢
[解决办法]

;
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

热点排行