PostgreSQL:如何连接多行数据

6

我有一个非常不寻常的问题。我想把具有相同ID的行拼接成一行。为了说明我的问题,让我提供一个示例。这是查询:

SELECT b.id AS "ID",
       m.content AS "Conversation"
FROM bookings b 
INNER JOIN conversations c on b.id = c.conversable_id AND c.conversable_type = 'Booking'
INNER JOIN messages m on m.conversation_id = c.id
WHERE b.state IS NOT NULL
GROUP BY 1,2
LIMIT 1000;

以下是输出结果:

ID     **Conversation
1223    "blah, blah, blah, blah"
1223    " ... blaaaah, blah.."
1223    "more blaaah"
1223    "last blah"
5000    "new id, with more blah"
5000    "and the blah continues"

有没有一种方法可以将对话行连接成一个聚合行,同时保留ID?
像这样:
ID     Conversation
1223    "blah, blah, blah, blah, ... blaaaah blah.. more blaaah, last blah"
5000    "new id, with more blah and the blah continues"

我相信有一种有效的方法来做这件事,只是我自己想不出来。


group_concat() 是你的好朋友。 - wildplasser
1
可能是使用 string_agg() 函数吗? - wildplasser
快速问题。我如何为每个新消息创建一个换行? - DBE7
没有换行符。您可以使用 string_agg(colx, e'\n'),但它仍将是输出记录字段的一部分。 - wildplasser
1个回答

6

我能够通过查看这个问题的精彩答案来解决自己的问题。它只需要使用PostgreSQL的string_agg()函数即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接