简体   繁体   English

如何连接 SQL 中乱序的字符串碎片消息

[英]How do I concatenate fragmented messages of strings that are out of order in SQL

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):我有一个包含三列的表,第一列表示消息 ID(message_id),第二列表示指示消息顺序的序数特征(message_order),最后第三列是消息的片段(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? SQL 中是否有办法按消息顺序按消息连接消息行? 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:在 Postgres 中,您可以为此使用string_agg()

select message_Id, string_agg(message, ' ' order by message_order)  as message
from the_table
group by message_id;

For Oracle:对于 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:对于 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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