我想将单个col数据分成多列。 我有一列名为LocationCode的列,该列在表中的长度是可变的。
样本数据:
LocationCode (col name)
100.23432.356345.6765634.34324.5645.F
100.2343.565465.56756765756756.4535435345.76466.F
200.234324234.46565466456.678678678678.543545445.43243243.F
1502.23.5.56546.7657767575.567567.MGR
注意:将所有这些都分成不同的列。 预期输出:
Column1 Column2 Column3 Column4 Column5 Column6 Column7
100 23432 356345 6765634 34324 5645 F
100 2343 565465 56756765756756 4535435345 76466 F
200 234324234 46565466456 678678678678 543545445 43243243 F
1502 23 5 56546 7657767575 567567 MGR
我的样本数据由定界符分隔。和整数值的长度不同。 新形成的列应由定界符分隔。
答案 0 :(得分:2)
您正在寻找 PIVOT
/toolchain.py recipes:
audiostream master
click master
curly master
cymunk master
distribute 0.7.3
ffmpeg 2.6.3
ffpyplayer v3.2
flask master
freetype 2.5.5
hostlibffi 3.2.1
hostpython2 2.7.1
hostpython3 3.7.1
ios master
itsdangerous master
jinja2 master
kivent_core master
kivy 1.10.1
libcurl 7.65.3
libffi 3.2.1
libjpeg v9a
libpng 1.6.26
markupsafe master
numpy 1.9.1
openssl 1.0.2k
photolibrary master
pil 2.8.2
plyer master
pycrypto 2.6.1
pykka 1.2.1
pyobjus master
python2 2.7.1
python3 3.7.1
pyyaml 3.11
sdl2 2.0.8
sdl2_image 2.0.0
sdl2_mixer 2.0.0
sdl2_ttf 2.0.12
werkzeug master
这将为您生成7列(仅7列),如果您有更多或更少的列,则可以使用动态PIVOT。
答案 1 :(得分:0)
XML方法可能更简洁,但这是分而治之的方法
with cte1 as
(select col,charindex('.',col,charindex('.',col,(charindex('.',col)+1))+1) ind from table)
,cte2 as
(SELECT col, right(col,len(col)-ind) p1, left(col,ind-1) p2 from cte1)
select
col,
parsename(p2,3) col1,
parsename(p2,2) col2,
parsename(p2,1) col3,
parsename(p1,4) col4,
parsename(p1,3) col5,
parsename(p1,2) col6,
parsename(p1,1) col7
from cte2;
答案 2 :(得分:0)
使用cte和条件聚合的另一种解决方案:
with cte1(LocationCode, code, seqnum) as
(
select LocationCode, value as code,
row_number() over(partition by LocationCode order by (select null)) as seqnum
from location
cross apply string_split(LocationCode, '.')
)
select LocationCode,
max(case when seqnum = 1 then rtrim(code) end) as Column1,
max(case when seqnum = 2 then rtrim(code) end) as Column2,
max(case when seqnum = 3 then rtrim(code) end) as Column3,
max(case when seqnum = 4 then rtrim(code) end) as Column4,
max(case when seqnum = 5 then rtrim(code) end) as Column5,
max(case when seqnum = 6 then rtrim(code) end) as Column6,
max(case when seqnum = 7 then rtrim(code) end) as Column7
from cte1
group by LocationCode