1. 程式人生 > >Sybase資料庫實現等效的mysql中group_concat功能

Sybase資料庫實現等效的mysql中group_concat功能

在MySQL中,如果想實現將分組之後的多個數據合併到一列,可以使用group_concat函式,如下圖所示:
這裡寫圖片描述
但是,在Sybase中沒有這樣的函式(別問我為什麼使用Sybase,因為公司用的Sybaseo(╯□╰)o)。因為我的Sybase是ASE的,使用變數累計的方法實現了該功能。憋說話,看程式碼:

IF OBJECT_ID('#test') IS NOT NULL
      drop table #test
go
CREATE TABLE #test(
id int null
,comment varchar(100) null
)
GO

insert into #test values
(1,'111') insert into #test values(1,'222') insert into #test values(1,'333') insert into #test values(1,'444') insert into #test values(1,'555') insert into #test values(1,'666') insert into #test values(1,'777') insert into #test values(2,'123') insert into #test values(2,'456') insert into #test values
(2,'789') insert into #test values(2,'012') insert into #test values(2,'345') insert into #test values(2,'678') insert into #test values(3,'123') insert into #test values(3,'456') insert into #test values(3,'789') insert into #test values(4,'123') insert into #test values(4,'456') insert into #test values
(5,'234') insert into #test values(6,'345') insert into #test values(7,'789') GO BEGIN declare @cc varchar(500) declare @cc1 int declare @num int set @cc='' set @num=1 select id,comment,space(500) as sub_comment,0000 as lev into #tt from #test order by id update #tt set sub_comment=(case when @cc1=id then @cc || ',' || comment else comment end) ,@cc=(case when @cc1=id then @cc || ',' || comment else comment end) ,lev=(case when @cc1=id then @num+1 else 1 end) ,@num=(case when @cc1=id then @num+1 else 1 end) ,@cc1=id select t.id,t.sub_comment from #tt t inner join (select id, max(lev) as tl from #tt group by id) c on t.id=c.id and t.lev=c.tl --如果一個分組中的comment多於5個,最多顯示5個comment -- select t.id,t.sub_comment -- from #tt t inner join (select id, (case when max(lev) > 5 then 5 else max(lev) end) as tl from #tt group by id) c -- on t.id=c.id and t.lev=c.tl truncate table #tt drop table #tt END