有下表(描述对话):
id | record_id | is_response | text |
---+------------+---------------+----------------------+
1 | 1 | false | first line of text |
2 | 1 | true | second line of text |
3 | 1 | false | third line of text |
4 | 1 | true | fourth line of text |
5 | 1 | true | fifth line of text |
6 | 2 | false | first line of text |
7 | 2 | true | second line of text |
8 | 2 | false | third line of text |
9 | 2 | true | fourth line of text |
10 | 2 | true | fifth line of text |
我正在寻找一个SQL查询来输出以下内容:
record_id | in_text | out_text
----------+-----------------------+---------------------
1 | first line of text | second line of text
----------+-----------------------+---------------------
1 | first line of text |
| second line of text |
| third line of text | fourth line of text
----------+-----------------------+---------------------
1 | first line of text |
| second line of text |
| third line of text |
| fourth line of text | fifth line of text
----------+-----------------------+---------------------
2 | first line of text | second line of text
----------+-----------------------+---------------------
2 | first line of text |
| second line of text |
| third line of text | fourth line of text
----------+-----------------------+---------------------
2 | first line of text |
| second line of text |
| third line of text |
| fourth line of text | fifth line of text
含义每次is_response列为true时,将text列作为in_text进行累积,并将新行添加为out_text.
行的顺序由id定义.
是否可以使用纯SQL?怎么样?
最佳答案 在子查询中使用聚合函数string_agg()作为窗口函数:
SELECT record_id, in_text, out_text
FROM (
SELECT record_id, text AS out_text, is_response
, string_agg(text, E'\n')
OVER (PARTITION BY record_id ORDER BY id
ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS in_text
FROM tbl
) sub
WHERE is_response;
这里的特殊功能是使用ROWS子句调整窗口框架.有关:
> Grouping based on sequence of rows
SQL Fiddle.(换行符转换为sqlfiddle中的空格.)