【问题标题】:How to split row into many rows in postgresql如何在postgresql中将行拆分为多行
【发布时间】:2016-02-20 17:46:11
【问题描述】:

我有一个包含两列的表格:ID 和汽车。 示例数据如下所示:

ID  |  Cars
-----------------
1   |  opel, honda and land rover
2   |  ford and porshe, damaged
3   |  volkswagen
4   |  opel, seat, damaged

我想把它分成:

ID  |  Cars
-----------------
1   |  opel
1   |  honda
1   |  land rover
2   |  ford
2   |  porshe, damaged
3   |  volkswagen
4   |  opel
4   |  seat, damaged

所以分隔符是and, 但不是, damaged postgresql中如何使用regex进行拆分?

编辑:

以及如何使它适用于像这样的记录

5 | land rover and opel, and ford
6 | ford; mazda and toyota

【问题讨论】:

  • “porshe”是什么车?

标签: sql regex postgresql


【解决方案1】:

您可以使用regexp_split_to_table 对损坏进行负前瞻;

SELECT "ID", regexp_split_to_table("Cars", '((, (?!damaged))| and )') "Cars" 
FROM mytable;

 ID |      Cars
----+-----------------
  1 | opel
  1 | honda
  1 | land rover
  2 | ford
  2 | porshe, damaged
  3 | volkswagen
  4 | opel
  4 | seat, damaged
(8 rows)

An SQLfiddle to test with.

编辑:对于您的新示例,必须稍微调整正则表达式;

SELECT "ID", regexp_split_to_table("Cars", '(([,;] (?!damaged))|[,;]? and )') "Cars" 
FROM mytable;

Another SQLfiddle.

【讨论】:

  • 感谢您的快速回复!以及如何添加新行?因为这只是选择查询。谢谢!
  • @Mateusz 也许您可以为此添加一个新问题,其中包含更多信息和示例,该问题甚至没有提及插入新行或输入或结果格式应该是什么。
  • 然后我会重复我的问题,我认为这在 stackoverflow 上不合适
  • @Mateusz 好吧,您有问题所涉及的选择部分,我正在考虑您在问题中未提及的 cmets 中询问的插入:)
  • @Mateusz 因为这将是一个具有新功能的实质性编辑,所以最好提出一个新的(自包含的)问题。如果需要,您可以随时添加指向此问题的链接作为解释的一部分。
猜你喜欢
  • 2017-09-20
  • 2021-08-21
  • 2023-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-11
  • 2010-09-15
相关资源
最近更新 更多