【发布时间】:2011-09-16 04:10:52
【问题描述】:
我有以下数据
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
我们要做的是,数字字符的数量必须用那些破折号('-')替换,然后我们需要合并相应 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,-,-,-,
也就是说,我无法在字符之间放置破折号('-')。
请帮忙
【问题讨论】:
标签: sql sql-server sql-server-2005 tsql common-table-expression