簡體   English   中英

SQL-獲取一列,將其拆分為新列

[英]SQL - Take a Column, Split it into New Columns

表格示例:

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

注意:每個字符用空格分隔。 注意:CB中的字符數有所不同。

我想將CB列中的每個字符(在第一個字符之后)移到其自己的單獨的列中,以便每列中不超過一個字符。

像這樣:

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

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

(SQLite的)

在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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM