我正在尝试将此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, ''
会这样做。任何帮助都将不胜感激。
感谢。
答案 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