Sybase数据库实现等效的mysql中group_concat功能

在MySQL中,如果想实现将分组之后的多个数据合并到一列,可以使用group_concat函数,如下图所示:

Sybase数据库实现等效的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

参考: http://bbs.csdn.net/topics/370026432

上一篇:吴裕雄 python 机器学习——线性判断分析LinearDiscriminantAnalysis


下一篇:Head First 设计模式 —— 02. 观察者 (Observer) 模式