【问题标题】:SQLite - Combining Rows into New ColumnsSQLite - 将行组合成新列
【发布时间】:2021-01-11 02:46:24
【问题描述】:

我正在尝试使用自己的文本消息在 Python 3.9 中创建聊天机器人,但无法正确格式化我的数据。

我有一个如下所示的短信表:

row_id Type Date Text
1 Incoming 2020-08-10 08:09:18 Hi
2 Outgoing 2020-08-10 08:11:04 Hello
3 Incoming 2020-08-10 08:11:12 For tomorrow
4 Incoming 2020-08-10 08:11:20 Are we still on for dinner?
5 Outgoing 2020-08-10 08:11:31 Let me check.
6 Outgoing 2020-08-10 08:11:43 Yes
7 Incoming 2020-08-10 08:11:45 Great!

我需要做的是将最后一个和下一个传出之间的所有传入文本,以及最后一个和下一个传入之间的所有传出文本合并到一个列中。

例如,上表应如下所示:

Incoming Outgoing
Hi Hello
For Tomorrow Are we still on for dinner? Let me check. Yes
Great

对话有超过 17,000 条记录。 我正在使用 sqlite3 在 Python 3.9 中运行它。

我将如何完成这项任务?

【问题讨论】:

  • 提示:看看解析函数->lead()
  • 当有多个传出消息与一个传入消息相关时会发生什么,反之亦然?请附上一张表格,显示您希望看到的内容。
  • @ggordon 给出的样本数据实际上已经有这些边缘情况。

标签: python sql sqlite


【解决方案1】:

这是一个空白和孤岛问题。我们可以在这里结合字符串聚合使用行数差异法:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY Date) rn1,
              ROW_NUMBER() OVER (PARTITION BY Type ORDER BY Date) rn2
    FROM yourTable
),
cte2 AS (
    SELECT *, rn1-rn2 AS grp, DENSE_RANK() OVER (PARTITION BY Type ORDER BY rn1-rn2) rnk
    FROM cte
    ORDER BY grp, rnk
)

SELECT
    GROUP_CONCAT(CASE WHEN Type = 'Incoming' THEN TEXT END, ' ') AS Incoming,
    GROUP_CONCAT(CASE WHEN Type = 'Outgoing' THEN TEXT END, ' ') AS Outgoing
FROM cte2
GROUP BY
    rnk
ORDER BY
    rnk;

Demo

【讨论】:

    【解决方案2】:

    您可以按如下方式使用解析函数和条件聚合:

    Select group_concat(case when type = 'incoming' then text end, ' ') as incoming_msg,
           Group_concat(case when type = 'outgoing' then text end, ' ') as outgoing_msg
      From
    (Select t.*,
           Sum(case when type = lg_type then 0 else 1 end) over (order by date) as sm
      From
    (Select t.*,
           Lag(type) over (order by date) as lg_type
      From t) t) t
    Group by sm
    

    【讨论】:

      猜你喜欢
      • 2014-07-11
      • 1970-01-01
      • 2014-06-27
      • 1970-01-01
      • 2013-12-31
      • 2013-06-15
      • 1970-01-01
      • 1970-01-01
      • 2020-06-14
      相关资源
      最近更新 更多