T-SQL中的填充函数可将复制n次的值连接起来

时间:2019-02-28 05:57:44

标签: sql sql-server sql-server-2012

select    
    TM.Tranaction_Slno,TT.Location,
    [Container Number] = stuff((select ',' + TD.Container_Number 
                                from Transaction_Data 
                                for xml path('')), 1, 1, '')   
from 
    Transaction_Master TM         
inner join 
    Transaction_Data TD on TD.Tranaction_Slno = TM.Tranaction_Slno        
left join 
    Transaction_Track TT on TT.Transaction_Slno = TM.Tranaction_Slno 
where 
    TM.Tranaction_Slno = 1770575 

我得到的输出带有重复n次的串联值。输出如下:

enter image description here

此屏幕截图显示了不使用填充功能的情况:

enter image description here

我想要这样的输出:

Transaction_Slno    Location    Container_Number
----------------------------------------------------------
1770575             CUSTOM       ZIMU1374787,TRHU3437713
1770575             ZERO         ZIMU1374787,TRHU3437713
1770575             CFS          ZIMU1374787,TRHU3437713

2 个答案:

答案 0 :(得分:2)

您可以尝试使用不同的代码,还需要在xml路径代码中添加where条件吗?

select  
        TM.Tranaction_Slno,TT.Location,
        [Container Number] = stuff((select distinct  ',' + Container_Number 
                                    from Transaction_Data TD1 
                                    where TD1.Transaction_Slno=TD.Transaction_Slno
                                    and  TD1.Location=TD.Location
                                    for xml path('')), 1, 1, '')   
    from 
        Transaction_Master TM         
    inner join 
        Transaction_Data TD on TD.Tranaction_Slno = TM.Tranaction_Slno  and  TM.Location=TD.Location      
    left join 
        Transaction_Track TT on TT.Transaction_Slno = TM.Tranaction_Slno and  TM.Location=TT.Location
    where 
        TM.Tranaction_Slno = 1770575 

答案 1 :(得分:2)

您可以尝试使用组串联逻辑,如下所示:

SELECT
    tm.Transaction_Slno,
    tt.Location,
    [Container Number] = STUFF((
        SELECT ',' + td.Container_Number
        FROM Transaction_Data td
        WHERE td.Transaction_Slno = tm.Transaction_Slno
        FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM Transaction_Master tm
INNER JOIN Transaction_Track tt
    ON tt.Transaction_Slno = tm.Transaction_Slno
ORDER BY
    tm.Transaction_Slno;

当前调用STUFF的主要逻辑问题是,它不会将针对Transaction_Data表的查询与查询所涉及的其他表相关联。