如何使用Stuff()将Oracle LISTAGG()函数转换为SQL Server

时间:2014-07-17 17:50:05

标签: oracle sql-server-2008 tsql concatenation

我正在尝试将此Oracle脚本转换为T-SQL:

Oracle代码:

Select Col1, Col2, Col3, Col4,
       'BDS: ' || LISTAGG(BD, ' , ') WITHIN GROUP (ORDER BY Col5, Col6) || '.' AS BDs
from(Select Col1, Col2, Col3, Col4, Col5, Col6,
             to_char(Col7) || '-' || Col8 || '-' || to_char(Col5) || '-' || to_char(Col6) BD
     from TBL1
     order by Col6)
Group BY Col1, Col2, Col3, Col4

示例结果:

    COl1 | COl2 | COl3 | Col4 | BDS
    Z1   | 1    | 12   | 1    | BDS: 1-M-12-6-1 + 1-M-12-6-2 + 1-M-12-6-3
    Z1   | 1    | 31   | 1    | BDS: 1-M-31-6-5 + 1-M-31-6-6 + 1-M-31-6-7

到目前为止,我已经尝试过,

Select 
    Col1, Col2, Col3, Col4,
    'BDS: ' + STUFF (select ' , ' + BD
                     from TBL1
                     group by BD
                     order by Col5, Col6    
                     FOR XML PATH('')), 1, 1, '') + '.' AS BDS    
from 
    (select 
        Col1, Col2, Col3, Col4, Col5, Col6,
        CONVERT(VARCHAR,Col7) + '-' + Col8+ '-' + CONVERT(VARCHAR,Col5)   + '-' + CONVERT(VARCHAR,Col6) BD
     from TBL1) A1
Group By 
   Col1, Col2, Col3, Col4, BD

结果:

     COl1 | COl2 | COl3 | Col4 | BDS
     Z1   | 1    | 12   | 1    | BDS: + 1-M-12-6-1 + 1-M-12-6-1 + 1-M-12-6-1......(repeats for more than 100 times)
     Z1   | 1    | 12   | 1    | BDS: + 1-M-12-6-2 + 1-M-12-6-2 + 1-M-12-6-2......(repeats for more than 100 times)

问题:

  • Col3需要具有唯一值
  • BDS如果Col3中的相应值相同,则需要连接字符串
  • 需要从+列中删除第一次出现的BDS,我认为FOR XML PATH('')), 1, 1, ''会这样做。

任何帮助都将不胜感激。

感谢。

1 个答案:

答案 0 :(得分:0)

我解决了,下面是脚本

Select 
Col1, Col2, Col3, Col4,
'BDS: ' + STUFF (select ' , ' + BD
                 from (select Col1, Col2, Col3, Col4, Col5, Col6,
                       CONVERT(VARCHAR,Col7) + '-' + Col8+ '-' + CONVERT(VARCHAR,Col5)   + '-' + CONVERT(VARCHAR,Col6) BD
                       from TBL1) A1
                 where A1.col1 =A2.col1 and
                       A1.col2 = A2.col2 and
                       A1.col3 = A2.col3 and
                       A1.col4 = A2.col4 and
                       A1.col5 = A2.col5 and
                       A1.col6 = A2.col6
                 order by Col5, Col6    
                 FOR XML PATH('')), 1, 2, '') + '.' AS BDS    
from 
(select 
    Col1, Col2, Col3, Col4, Col5, Col6,
    CONVERT(VARCHAR,Col7) + '-' + Col8+ '-' + CONVERT(VARCHAR,Col5)   + '-' + CONVERT    (VARCHAR,Col6) BD
     from TBL1) A2
Group By 
Col1, Col2, Col3, Col4