当前位置: 代码迷 >> Sql Server >> 再求sql,最近发春,一直会想起好多sql要写,该如何处理
  详细解决方案

再求sql,最近发春,一直会想起好多sql要写,该如何处理

热度:90   发布时间:2016-04-27 12:56:41.0
再求sql,最近发春,一直会想起好多sql要写
某表tb,一列a
a
str1
str2
str3
str4
str5
str6
str7
str8
....
想把每两行的字符串连接起来,如
a
str1str2
str3str4
str5str6
......

再求高手





------解决方案--------------------
--sql 2000用函数解决:
SQL code
create table tb(a varchar(10))insert into tb values('str1')insert into tb values('str2')insert into tb values('str3')insert into tb values('str4')insert into tb values('str5')insert into tb values('str6')insert into tb values('str7')insert into tb values('str8')go--创建函数解决:create function dbo.f_str(@px int) returns varchar(1000)asbegin  declare @str varchar(1000)  select @str = isnull(@str , '') + cast(a as varchar) from (select t.* , px = (((select count(1) from tb where a < t.a) + 1) - 1)/2 from tb t) m where px = @px  return @strendgo--调用函数select dbo.f_str(px) a from(  select t.* , px = (((select count(1) from tb where a < t.a) + 1) - 1)/2 from tb t) mgroup by pxdrop function dbo.f_strdrop table tb/*a                     ----------------------str1str2str3str4str5str6str7str8(所影响的行数为 4 行)*/
------解决方案--------------------
探讨

--sql 2000用函数解决:
SQL code
create table tb(a varchar(10))
insert into tb values('str1')
insert into tb values('str2')
insert into tb values('str3')
insert into tb values('str4')
insert into tb value……

------解决方案--------------------
--sql 2005
SQL code
create table tb(a varchar(10))insert into tb values('str1')insert into tb values('str2')insert into tb values('str3')insert into tb values('str4')insert into tb values('str5')insert into tb values('str6')insert into tb values('str7')insert into tb values('str8')goselect a = replace(stuff((select ',' + a from (  select t.* , px = (row_number() over(order by a) - 1)/2 from tb t) m where m.px = n.px for xml path('')) , 1 , 1 , ''),',','')from (  select t.* , px = (row_number() over(order by a) - 1)/2 from tb t) ngroup by pxdrop table tb/*a------------str1str2str3str4str5str6str7str8(4 行受影响)*/
------解决方案--------------------
SQL code
--> --> (Roy)生成測試數據 if not object_id('Tempdb..#a') is null    drop table #aGoCreate table #a([Col] nvarchar(4))Insert #aselect N'str1' union allselect N'str2' union allselect N'str3' union allselect N'str4' union allselect N'str5' union allselect N'str6' union allselect N'str7' union allselect N'str8'Go;with aas(Select *,ROW_NUMBER()over(order by getdate()) as row from #a)select     a.[Col]+ISNULL(b.[Col],'') as Str1from a    left join a as b on a.row=b.row-1where a.row%2=1/*str1str2str3str4str5str6str7str8*/
  相关解决方案