我有以下数据使用FOR XML Path的sql server中的字符串连接问题。
UniqueID ID data
1 1 a
2 1 2
3 1 b
4 1 1
5 2 d
6 2 3
7 2 r
预期的输出是
ID ConcatData
1 a,-,-,b,-
2 d,-,-,-,r
我们要做的是什么,数字charecters的数量必须与许多破折号(替换“ - ” ),然后我们需要合并各自ID的数据。
我使用下面的查询到目前为止
declare @t table(UniqueID int identity(1,1), ID int, data varchar(10))
insert into @t select 1, 'a' union all select 1, '2' union all select 1, 'b'
union all select 1, '1' union all select 2, 'd' union all select 2, '3'
union all select 2, 'r'
select * from @t
;with cte1 as
(
select
UniqueId
, id
, data
, case when isnumeric(data) = 1 then cast(data as int) end Level
from @t
union all
select
UniqueId
, id
, CAST('-' as varchar(10))
, Level - 1
from cte1
where Level > 0)
,cte2 as
(
select id, GroupID = Dense_Rank() Over(Order by id),data, DataOrder = ROW_NUMBER() over(order by UniqueID, Level)
from cte1
where Level is null or data = '-'
)
SELECT
ID
, (select data + ','
from cte2 t2
where t2.GroupID = t1.GroupID
for XML path('')
) as ConcatData
from cte2 t1
group by t1.ID ,t1.GroupID
但输出
ID ConcatData
1 a,b,-,-,-,
2 d,r,-,-,-,
这是我不能给短线的位置 - 在字符之间(“”)。
请帮
谢谢你学习关于复制的新东西。我同意,你的建议更好。谢谢:) – Pankaj 2011-06-16 11:06:34
+1复制 – Pankaj 2011-06-16 11:07:50