SQL - XML PATH(''=

时间:2017-11-08 09:03:27

标签: sql sql-server tsql concatenation

我需要帮助来连接三个表:

Table1               Table 2 (Rel)                Table 3
ID   Desc            IDTable1   IDTable3          ID      Descr  
1    desc1               1          1             1        Nome1
2    desc2               2          1             2        Nome2
3    desc3               3          1
                         1          2
                         3          2  

结果如下:

New Table
    CName        Cname2
    Nome1           desc1,desc2,desc3
    Nome2           desc1,desc3

我试过这样的方式:

Select t3.descr,
    STUFF((SELECT '\n' + t1.desc  as [text()] from Table1 t1 inner join Table2 t2 on t1.ID = t2.idtable1
    inner join Table3 t3 on t3.ID = t2.IDTable3 order by t1.Desc FOR XML PATH('')), 1, 1, '' ) AS Cname2 
from  Table3 t3 inner join Table2 t2 on t3.ID = t2.IDTable3
where IDTable1 = '9A02C9C1-76B9-E711-A964-005056B10019'
group by t3.descr

我试过了,但结果如下:

New Table
    CName        Cname2
    Nome1           desc1,desc2,desc3,desc1,desc3
    Nome2           desc1,desc2,desc3,desc1,desc3

你能帮助我吗?

1 个答案:

答案 0 :(得分:0)

您的解决方案中有两次t3别名,因此,您的子查询不依赖于外部查询。这就是为什么两个Descr值具有相同的值列表的原因。我想你想要这样的东西:

Select t3.descr,
    STUFF(
      (SELECT '\n' + t1.desc  as [text()] 
       from Table1 t1 
       inner join Table2 t2 on t1.ID = t2.idtable1
       where t3.ID = t2.IDTable3 
       order by t1.Desc 
       FOR XML PATH('')), 1, 1, '' ) AS Cname2 
from  Table3 t3 
inner join Table2 t2 on t3.ID = t2.IDTable3
where IDTable1 = '9A02C9C1-76B9-E711-A964-005056B10019' 
group by t3.ID, t3.descr

我已将t3.ID添加到您的GROUP BY中,以便可以在子查询中使用。