【问题标题】:Concatenate values from SELECT with delimiter in ORACLE将 SELECT 中的值与 ORACLE 中的分隔符连接起来
【发布时间】:2021-07-27 11:43:16
【问题描述】:

我有表products,我想创建字符串:

http://localhost/app/feeds/send?type=myType&ids=1,2,3,...,100
http://localhost/app/feeds/send?type=myType&ids=101,102,103,...,200

我创建了 sql 查询:

select concat('http://localhost/app/feeds/send?type=myType' || CHR(38) || 'ids=' , product_id) from products where isin like 'AC%' and status in
('Active', 'Created', 'Live')
and
((date>to_date('07.05.2021','dd.MM.yyyy') or date is null));

它似乎几乎是我需要的,但结果是:

http://localhost/app/feeds/send?type=myType&ids=1
http://localhost/app/feeds/send?type=myType&ids=2
http://localhost/app/feeds/send?type=myType&ids=3

如何更改此查询以返回 100 ids 和分隔符 ,?

【问题讨论】:

  • 样本数据会有所帮助。

标签: sql oracle select sqlplus listagg


【解决方案1】:

您可以在 Oracle 中使用 LISTAGG 函数。

select 'http://localhost/app/feeds/send?type=myType' || CHR(38) || 'ids=' ||

  LISTAGG(product_id,',') WITHIN GROUP (ORDER BY product_id)

from products where isin like 'AC%' and status in
('Active', 'Created', 'Live')
and
((pdate>to_date('07.05.2021','dd.MM.yyyy') or pdate is null));

DB Fiddle

【讨论】:

  • 你还知道如何按 100 行分组吗?没有它 ORA-01489: 字符串连接的结果太长。我可以添加and ROWNUM <= 100;,但是只有 100 行,不像在循环中
  • 我用了这个答案:stackoverflow.com/a/40754382/4952262
【解决方案2】:

删除 Concat 函数,你不需要它。

使用将 id 1 到 100 与 101 到 200 分开的任何字段添加 Group By 子句。

然后让您的查询使用 ListAgg() 聚合函数(如 ListAgg(id,','))返回一列。第一个参数是您要聚合的字段 (id),第二个参数是要在两条记录之间使用的分隔符。

【讨论】:

    猜你喜欢
    • 2023-01-03
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-13
    相关资源
    最近更新 更多