将结果减少为累积组

时间:2016-08-31 11:36:30

标签: sql postgresql grouping window-functions

拥有下表(描述对话):

 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时,表示将文本列累加为in_text,并将新行添加为out_text

行的顺序由id定义。

是否可以使用纯SQL?怎么样?

1 个答案:

答案 0 :(得分:1)

在子查询中使用聚合函数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子句调整窗口框架。相关:

SQL Fiddle.(换行符转换为sqlfiddle中的空格。)