SQL根据字符串模式将单列转换为多行

时间:2018-06-06 07:09:11

标签: sql postgresql split

我有一张包含以下样本数据的表格:

id, query
----------
25, normal query
25, query with brackets (example1) 
46, brackets in query (example2) (example3)
55, text1 (example4) text2

对于带括号的查询,我想在表格中添加一行,其中包含每个括号中的信息,如下所示:

id, query
----------
25, normal query
25, query with brackets
25, example1
46, brackets in query
46, example2
46, example3
55, text1 text2
55, example4

我可以轻松识别带有LIKE '%(%)%'括号的行,但是我不确定如何拆分和添加新行。

谢谢!

1 个答案:

答案 0 :(得分:3)

select 
  id,
  regexp_split_to_table(
    replace(query,')','')
  ,E'\\(') query
from TestTable

<强>结果:

| id |                query |
|----|----------------------|
| 25 |         normal query |
| 25 | query with brackets  |
| 25 |             example1 |
| 46 |   brackets in query  |
| 46 |            example2  |
| 46 |             example3 |

SQL Fiddle Demo Link

新问题:

  

谢谢!!你可以请新的55行帮忙吗?我已经对问题进行了编辑并要求输出。

select 
  id,
  regexp_split_to_table(
    replace(
      replace(
        replace(
          query
          ,') (','(')        
        ,') ','( ')
    ,')','')
  ,E'\\(') query
from TestTable

<强>结果:

| id |                query |
|----|----------------------|
| 25 |         normal query |
| 25 | query with brackets  |
| 25 |             example1 |
| 46 |   brackets in query  |
| 46 |             example2 |
| 46 |             example3 |
| 55 |               text1  |
| 55 |             example4 |
| 55 |                text2 |

SQL Fiddle Demo Link