I have a table with three columns the first column indicates a message ID (message_id) the second column represents an ordinal feature which indicates the order of the message (message_order), lastly the third column is a fragment of the message(message_fragment):
+------------+---------------+------------------------------+
| message_id | message_order | message |
+------------+---------------+------------------------------+
| Message 1 | 2 | Best, Jose |
| Message 1 | 1 | Thanks for your advice |
| Message 2 | 1 | I only have one line of text |
+------------+---------------+------------------------------+
Is there a way in SQL to concatenate the message rows by message in order of message order? To ultimately get the following:
+------------+-----------------------------------+
| message_id | message |
+------------+-----------------------------------+
| Message 1 | Thanks for your advice Best, Jose |
| Message 2 | I only have one line of text |
+------------+-----------------------------------+
In Postgres you can use string_agg()
for this:
select message_Id, string_agg(message, ' ' order by message_order) as message
from the_table
group by message_id;
For Oracle:
with msg(msg_id, msg_order, msg_text) as (
select 1, 2, 'Best, Jose' from dual union all
select 1, 1, 'Thanks for your advice' from dual union all
select 2, 1, 'I only have one line of text' from dual
)
select msg_id, listagg(msg_text, ' ') within group (order by msg_id, msg_order) message
from msg
group by msg_id;
For Hive:
select message_id, concat_ws(' ', collect_list(message)) as message
from
(select message_id, message_order, message
from table
distribute by message_id sort by message_order
)s
group by message_id
order by message_id;
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.