今天在群裡碰到一個問題,群友說是一道面試題,禁不住好奇,問題如下:
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 t
where type = 1 FOR XML AUTO),'<t strvalue="',' '),'"/>', ' ')+'#')+
(select replace(replace((SELECT strvalue FROM tb_test t
where type = 2 FOR XML AUTO),'<t strvalue="',' '),'"/>', ' ')+'#')
05裡面的測試通過
群裡有人給出了另一個實現方法:
SQL-CODE
declare @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都通用