Sybase ASE 15 字符串聚合函数

3

我正在寻找一种方法,在Sybase ASE 15中将来自不同行的字符串聚合成单行。就像这样:

id | Name                    Result: id | Names
-- - ----                            -- - -----
1  | Matt                            1  | Matt, Rocks
1  | Rocks                           2  | Stylus
2  | Stylus

类似于T-SQL中的FOR XML PATH。

谢谢!

5个回答

6

Sybase ASE没有像list()group_concat()这样的字符串聚合函数;虽然有一些FOR XML的支持,但它不包括PATH选项/功能的支持。

假设你需要添加未知/可变数量的行,你唯一的(ASE 15)T-SQL选项是基于游标的解决方案。

如果你发现自己使用的是ASE 16,你可以编写一个用户定义的函数(UDF)来完成任务,例如:在ASE 16中模拟group_concat()


1

编写以下查询: select id, cursorfunc(id) from table

然后创建以下游标,用于上述查询 DECLARE ListCurs CURSOR FOR

//查询获取名称 select name from table where id=@id

OPEN ListCurs SELECT @Status = 0 WHILE @Status = 0 BEGIN FETCH ListCurs INTO @name

IF @Status = 0 
BEGIN
   SELECT  @res = CASE WHEN @res IS NULL THEN '' ELSE @res + '& ' END + @name
END

END CLOSE ListCurs RETURN (@res)

结束 关闭ListCurs 返回(@res)


0
你试过使用 Select String_Agg(<Column>, '<Seperator>') From <Table Name> 吗?

string_agg()在SAP(Sybase)ASE中不是一个有效的(系统)函数。 - undefined

0
我知道这个问题有点老了,但最近我也遇到了这个问题,如果你假设列表中的名字数量有一个上限(例如我的例子中是10),那么这可能是一个解决方案。
    select id,
           max(case n
                 when 0 then Name
               end)
         + max(case n
                 when 1 then ','+ Name
               end)
         + max(case n
                 when 2 then ','+ Name
               end)
         + max(case n
                 when 3 then ','+ Name
               end)
         + max(case n
                 when 4 then ','+ Name
               end)
         + max(case n
                 when 5 then ','+ Name
               end)
         + max(case n
                 when 6 then ','+ Name
               end)
         + max(case n
                 when 7 then ','+ Name
               end)
         + max(case n
                 when 8 then ','+ Name
               end)
         + max(case n
                 when 9 then ','+ Name
               end) as Names
from (SELECT t.id,
             t.Name,
             count(t2.Name) as n
      FROM T t
           left join T t2
             on t2.id = t.id
            and t2.Name < t.name
      -- WHERE 
      group by t.id, t.Name) x
group by id

-3
你可以尝试这样做:
select id,list(Names,',' order by id) from TableName a group by id 

2
Sybase ASE 不支持 LIST() 函数。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接