【发布时间】:2016-09-26 15:36:15
【问题描述】:
在previous question 上,我问了一个类似的问题,该问题依赖于帮助表作为拆分数据的标准的一部分。看来我目前的目标比较容易,但我想不通。
给定表格:
CREATE TABLE conversations (id int, record_id int, is_response bool, text text);
INSERT INTO conversations VALUES
(1, 1, false, 'in text 1')
, (2, 1, true , 'response text 1')
, (3, 1, false, 'in text 2')
, (4, 1, true , 'response text 2')
, (5, 1, true , 'response text 3')
, (6, 2, false, 'in text 1')
, (7, 2, true , 'response text 1')
, (8, 2, false, 'in text 2')
, (9, 2, true , 'response text 2')
, (10, 2, true , 'response text 3');
我想根据is_response 值聚合文本并输出以下内容:
record_id | aggregated_text |
----------+---------------------------------------------------+
1 |in text 1 response text 1 |
----------+---------------------------------------------------+
1 |in text 2 response text 2 response text 3 |
----------+---------------------------------------------------+
2 |in text 1 response text 1 |
----------+---------------------------------------------------+
2 |in text 2 response text 2 response text 3 |
我试过下面的查询,但是没能连续聚合两个响应,IE :is_response 依次为真。
SELECT
record_id,
string_agg(text, ' ' ORDER BY id) AS aggregated_text
FROM (
SELECT
*,
coalesce(sum(incl::integer) OVER (ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),0) AS grp
FROM (
SELECT *, is_response as incl
FROM conversations
) c
) c1
GROUP BY record_id, grp
HAVING bool_or(incl)
ORDER BY max(id);
我的查询的输出只是为下面的 is_response 行添加了另一行,如下所示:
record_id | aggregated_text |
----------+---------------------------------------------------+
1 |in text 1 response text 1 |
----------+---------------------------------------------------+
1 |in text 2 response text 2 |
----------+---------------------------------------------------+
1 |response text 3 |
----------+---------------------------------------------------+
2 |in text 1 response text 1 |
----------+---------------------------------------------------+
2 |in text 2 response text 2 |
----------+---------------------------------------------------+
2 | response text 3 |
----------+---------------------------------------------------+
我该如何解决?
【问题讨论】:
-
看起来你需要一个窗口函数给我。
-
感谢您的回复,您能帮忙提供一个代码示例吗?
-
现在没有时间。只是想提供一个指针以供研究。
-
你看到我对你重复的问题的回答了吗?
-
我冒昧地将您的测试表作为
CREATE TABLE脚本提供。这是首选形式,使回答更容易。请记住提供您的 Postgres 版本。否则我们只能假设当前版本,这通常会引起混淆。
标签: sql postgresql aggregate-functions window-functions