【问题标题】:postgresql: SQL Query to merge the contents from multiple rows using another columnpostgresql:使用另一列合并多行内容的 SQL 查询
【发布时间】:2013-03-14 11:42:47
【问题描述】:

我的表格history 有以下列:

row_id, msgid, sender, receiver, chatcontent, transdate, transtime

每个聊天记录都作为单独的一行存储在表格中。

场景: 如果内容超过 2048 个字符,我的框架会将聊天内容拆分为多个脚本,数据存储在多行中,具有相同的详细信息,例如 msgid、发送者、接收者、transdate 和 transtime,只有聊天内容与 row_id 作为序列不同。

例如, 我在表格中的内容是

001, msgid1, mark@test.int, james@test.int, this is a long tes, 2013-03-13, 13:55:34
002, msgid1, mark@test.int, james@test.int, t message which is, 2013-03-13, 13:55:34
003, msgid1, mark@test.int, james@test.int,  splitted in multi, 2013-03-13, 13:55:34
004, msgid1, mark@test.int, james@test.int, ple rows, 2013-03-13, 13:55:34
005, msgid2, james@test.int, mark@test.int, yup i got you, 2013-03-13, 13:56:12

现在我想在单个查询中获取数据,该查询应该输出为

msgid1, mark@test.int, james@test.int, this is a long test message which is splitted in multiple rows, 2013-03-13, 13:55:34
msgid2, james@test.int, mark@test.int, yup i got you, 2013-03-13, 13:56:12

怎么做。我无法在单个查询中获取所有详细信息。我可以使用命令将聊天内容合并在一列中,但我不想硬编码 msgid 的值

SELECT array_to_string(array(SELECT chatcontent FROM history where msgid='msgid1'),'');

【问题讨论】:

    标签: postgresql merge multiple-columns


    【解决方案1】:
    SELECT
        msgid,
        sender,
        receiver,
        transdate,
        transtime,
        array_to_string(array(
            select chatcontent
            from history
            where msgid = h.msgid
            order by row_id
            ), ' '
        ) chatcontent
    from history h
    group by 1, 2, 3, 4, 5, 6
    order by 1
    

    【讨论】:

      猜你喜欢
      • 2021-05-01
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      • 2023-02-10
      • 2013-07-20
      • 1970-01-01
      • 1970-01-01
      • 2020-01-27
      相关资源
      最近更新 更多