如果您使用函数和光标,这非常简单:
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
您必须创建一个函数来组装连接的字符串:
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
如果每个唯一的 EVENT_ID 只调用一次函数会更有效,因此我们distinct
在子查询中选择 EVENT_ID:
select x.EVENT_ID as [Event ID], dbo.fnConcat(x.EVENT_ID) as Movements
from (
select distinct EVENT_ID
from tmp
) as x
go
然后清理:
drop table tmp
go
drop function fnConcat
go
结果如下:
Event ID Movements
----------- ---------------------------
55001 05 26 28 27 26 27 28 30 40
56215 06 11 22