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

不知咋描述,算是队列转换

2012-12-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


[其他解释]
当然查询也可以在一个视图基础上
将表s 表t 表sc合成一个视图
sindex    sname    tindex    tname
s1        张三     t1        他是谁
s1        张三     t2        不知道
s2        李四     t1        他是谁

最终要这样个结果就行了
sindex        sname        tindexs      tnames
s1            张三         t1,t2       他是谁,不认识
s2            李四         t1           他是谁
[其他解释]
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
[其他解释]
大神啊,真是不熟练,一点就破啊呵呵

热点排行