[英]Concatenating a column over multiple rows in Oracle 12c
I have a table of notes related to orders from an old terminal system in Oracle 12c. 我有一张与Oracle 12c中的旧终端系统的订单相关的注释表。 Each order reference has several lines of notes, ordered by a sequence number. 每个订单参考都有几行注释,按序号排序。
I want to concatenate all of the relevant notes together for each order reference so that I can try to pull some address data out of it. 我想将每个订单参考的所有相关注释连接在一起,以便我可以尝试从中提取一些地址数据。 The address data could be spread over several different sequence numbers. 地址数据可以分布在几个不同的序列号上。 The structure is: 结构为:
| 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 | | |
------------------------------------------------
What I would like to turn this into is: 我想将其转换为:
|--------|---------------------------------------------------------------------------|
| 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 |
|--------|---------------------------------------------------------------------------|
It would probably be good to trim each note row before concatenating but I also need to make sure that I put a space between the join of two rows, just in case someone has filled the full line with text. 在连接之前修剪每个音符行可能会很好,但是我还需要确保在两行的连接之间放置一个空格,以防万一有人用文本填充了整个行。 Oh and the sequences are out of order so I need to order by first too. 哦,顺序不对,所以我也需要先排序。
Thanks for your help! 谢谢你的帮助!
You can use listagg for this: 您可以为此使用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";
Also, note that order
is a reserved keyword in oracle. 另外,请注意, order
是oracle中的保留关键字。 Best use some other identifier or use "
to escape it. 最好使用其他一些标识符或使用"
将其转义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.