首页 > 解决方案 > SQL - 取一列,将其拆分为新列

问题描述

示例表:

  ID    CB        CB2   CB3   CB4    CB5
  ----  --------  ----  ----  ----  ----
  1     亀 龜 龜
  2     竜 龒 

注意:每个字符用空格隔开。注意:CB 中的字符数会有所不同。

我想将 CB 列中的每个字符(在第一个字符之后)移动到自己的单独列中,以便每列中不超过一个字符。

像这样:

  ID    CB    CB2   CB3   CB4    CB5
  ----  ----  ----  ----  ----  ----
  1      亀    龜    龜
  2      竜    龒

注意:新列名不需要具有示例中显示的格式。

(SQLite)

标签: sqlsqlite

解决方案


在 SQLite 中,您可以使用递归 CTE 来做到这一点。以下获取字符:

with recursive cte as (
      select id, substr(cb, 1, instr(cb, ' ') - 1) as chr,
             substr(cb, instr(cb, ' ') + 1) as rest, 1 as lev
      from t
      union all
      select id, substr(rest, 1, instr(rest || ' ', ' ') - 1) as chr,
             substr(rest, instr(rest || ' ', ' ') + 1) as rest, lev + 1 as lev
      from cte
      where rest <> ''
     )
select *
from cte;

您可以旋转这些 . . . 对于固定数量的列:

select id,
       max(case when lev = 1 then chr end) as chr_1,
       max(case when lev = 2 then chr end) as chr_2,
       max(case when lev = 3 then chr end) as chr_3
from cte
group by id;

这是一个DB Fiddle


推荐阅读