简体   繁体   中英

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. 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:

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. Best use some other identifier or use " to escape it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM