It is pretty straight forward if you use a function and a cursor:
use tempdb
go
create table tmp (
EVENT_ID int,
TEXT_FRO varchar(10),
TEXT_TO varchar(10)
)
go
insert into tmp values
(55001, NULL, '05'),
(55001, '05', '26'),
(55001, '26', '28'),
(55001, '28', '27'),
(55001, '27', '26'),
(55001, '26', '27'),
(55001, '27', '28'),
(55001, '28', '30'),
(55001, '30', '40'),
(56215, '06', '11'),
(56215, '11', '22')
go
You have to create a function to assemble the concatenated string:
create function fnConcat (@id int) returns varchar(255) as
begin
declare @rtn varchar(255) = '', @fro varchar(10), @to varchar(10), @cnt int = 1
declare cr cursor local for
select TEXT_FRO, TEXT_TO
from tmp
where EVENT_ID = @id
open cr
fetch next from cr into @fro, @to
while @@fetch_status = 0
begin
if @cnt = 1 and @fro is not null
set @rtn = @rtn + @fro + ' '
set @rtn = @rtn + @to + ' '
set @cnt = @cnt + 1
fetch next from cr into @fro, @to
end
close cr
deallocate cr
set @rtn = left(@rtn, datalength(@rtn) - 1)
return @rtn
end
go
It is more efficient if you only call the function one time per unique EVENT_ID, so we select the distinct EVENT_ID in a sub-query:
select x.EVENT_ID as [Event ID], dbo.fnConcat(x.EVENT_ID) as Movements
from (
select distinct EVENT_ID
from tmp
) as x
go
And then cleanup:
drop table tmp
go
drop function fnConcat
go
This is the result looks like this:
Event ID Movements
----------- ---------------------------
55001 05 26 28 27 26 27 28 30 40
56215 06 11 22
05 85 ??null, 06row? Which column will have nulls (if any) and is that how we know the first Movement? Also, will you have data (like before) where a value can occur multiple times for Movement in one row?