今天在群里碰到一个问题,群友说是一道面试题,禁不住好奇,问题如下:
id strvalue type
1 how 1
2 are 1
3 you 1
4 fine 2
5 thank 2
6 you 2
要求用sql把它们搜索出来成为这样的
#how are you#fine thank you#
下面这个Select XML是我实现的,没有格式化,有点乱。。。嘿嘿
SQL-CODE select (select '#'+replace(replace((SELECT strvalue FROM tb_test twhere type = 1 FOR XML AUTO),'
(select replace(replace((SELECT strvalue FROM tb_test t
where type = 2 FOR XML AUTO),'
05里面的测试通过
群里有人给出了另一个实现方法:
SQL-CODEdeclare @t table(id int identity(1,1),v varchar(10),t int,temp varchar(max))
insert @t
select v='how',t=1,temp=''
union all select 'are',1,''
union all select 'you',1,''
union all select 'fine',2,''
union all select 'thank',2,''
union all select 'you',2,''
declare @t1 int,@temp varchar(max)
set @temp=''
update @t set @temp=case when t=@t1 then @temp+' '+v else @temp+'#'+v end
,@t1=t,temp=@temp from @t
select max(temp)+'#' from @t
select * from @t
--#how are you#fine thank you#
2000和05都通用