【问题标题】:Concatenating a column over multiple rows in Oracle 12c在 Oracle 12c 中将列连接到多行
【发布时间】:2017-09-16 00:32:29
【问题描述】:

我有一张与 Oracle 12c 中旧终端系统的订单相关的注释表。每个订单参考都有几行注释,按序号排序。

我想将每个订单参考的所有相关注释连接在一起,以便我可以尝试从中提取一些地址数据。地址数据可以分布在几个不同的序列号上。结构是:

| SEQ | NOTE_TEXT                | ORDER | ... |
|-----|--------------------------|-------|-----|
| 1   | The address for this     |       |     |
| 2   | is 123 The Street, City, |       |     |
| 3   | County, Postcode         |       |     |
| 1   | This customer has ordered|       |     |
| 2   | this product on date     |       |     |
| 1   | Some other note          |       |     |
| 1   | This order is for A Smith|       |     |
| 2   | The address is 4 The Lane|       |     |
| 3   | City, County, Postcode   |       |     |
------------------------------------------------

我想把它变成:

|--------|---------------------------------------------------------------------------|
| ORDER  | NOTE_TEXT                                                                 |
|--------|---------------------------------------------------------------------------|
| ABC123 | The address for this is 123 The Street, City, County, Postcode            |
| DEF456 | This customer has ordered this product on date                            |
| GHI789 | Some other note                                                           |
| JKL012 | This order is for A Smith The address is 4 A Lane, City, County, Postcode |
|--------|---------------------------------------------------------------------------|

在连接之前修剪每个注释行可能会很好,但我还需要确保在两行的连接之间放置一个空格,以防有人用文本填充了整行。哦,顺序有问题,所以我也需要先订购。

感谢您的帮助!

【问题讨论】:

    标签: sql oracle oracle12c


    【解决方案1】:

    您可以为此使用 listagg:

    select "order" || listagg(seq, '') within group (order by seq) as "order",
        listagg(trim(note_text), ' ') within group (order by seq) as note_text
    from your_table
    group by "order";
    

    另外,请注意order 是oracle 中的保留关键字。最好使用其他标识符或使用" 转义它。

    【讨论】:

    • OP 没有在模拟输入的order 列中显示值,但很可能它们已经类似于ABC123; 1、2、3 不是seq 数字。所以,SELECT 的第一列可以是"order"。 (很高兴您也指出了 Oracle 保留字的误用!)
    • 感谢古尔维!是的,顶部的模拟输入应该有实际的订单号而不是空白:P 幸运的是,将表格放在一起的人使用了一个比“订单”更神秘的列名,这是我试图简化事情 -大笑。
    猜你喜欢
    • 2019-09-19
    • 2018-07-11
    • 2020-10-09
    • 2016-08-07
    • 1970-01-01
    • 2014-05-18
    • 1970-01-01
    • 2018-07-18
    • 2014-06-12
    相关资源
    最近更新 更多