【发布时间】:2016-12-09 18:20:30
【问题描述】:
所以,我有一个非常规的问题。我希望能够将具有相同 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()是你的朋友。 -
可能是。那么可能是
string_agg()? -
快速提问。如何为每条新消息换行?
-
没有换行符。您可以使用
string_agg( colx, e'\n' ),但它仍然是输出记录字段的一部分。
标签: sql postgresql