请教一个行转列的问题,急!!
表A:
userid content visittime
a1 aaa 07:10:12
a1 bbb 07:15:00
a1 ccc 09:20:00
a2 aaa 07:12:10
a2 bbb 09:40:00
希望得到这样的表B:
results
aaa,bbb
ccc
aaa
bbb
即对于同一个userid的所有记录中,如果visittime间隔跟上条记录相差小于120minutes,就把该记录的content拼在上条记录的content后面,用逗号隔开,最终结果放在B表中。反之则作为新的记录放到B中。
B中只有一个字段。
A中已经处理过,同一个userid的数据都按照visittime升序排开了
------解决方案----------------------建立测试环境,新增的id列用来做主键
create table #tb(id int identity,userid varchar(10),content varchar(10),visittime datetime,results varchar(20))
insert #tb(userid,content,visittime)
select 'a1 ', 'aaa ', '07:10:12 ' union all
select 'a1 ', 'bbb ', '07:15:00 ' union all
select 'a1 ', 'ccc ', '09:20:00 ' union all
select 'a2 ', 'aaa ', '07:12:10 ' union all
select 'a2 ', 'bbb ', '09:40:00 '
go
--执行测试语句
declare @id varchar(10),@content varchar(10),@time datetime
update #tb
set @content = case when @id = userid and datediff(mi,@time,visittime) < 120 then @content + ', '+ content else content end
,@id = userid,@time = visittime,results = @content
select userid,results from #tb t
where not exists(select 1 from #tb where t.userid = userid and datediff(mi,t.visittime,visittime) < 120
and datediff(mi,t.visittime,visittime) > 0 and t.id <> id)
go
--删除测试环境
drop table #tb
go
/*--测试结果
userid results
---------- --------------------
a1 aaa,bbb
a1 ccc
a2 aaa
a2 bbb
(4 row(s) affected)
*/
------解决方案--------------------create function fn_test (@userid varchar(10), @visittime datetime)
returns varchar(50)
as
BEGIN
declare @str varchar(50)
select @str = ', ' + content from A where userid = @userid and datediff(mi,visittime,@visittime) <=120 and visittime <=@visittime
set @str = stuff(1,1, ' ')
return @str
END
go
select max(content) from
(select userid,content = dbo.fn_test(userid,visittime) visittime from A)C
group by userif,visittime