2014-07-17 63 views
1

我想此Oracle腳本轉換爲T-SQL:如何使用的東西()甲骨文LISTAGG()函數轉換到SQL Server

甲骨文代碼:

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, ''會做。

任何幫助,將不勝感激。

謝謝。

回答

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