Sas*_*aju 3 sql sql-server string user-defined-functions sql-server-2012
我有一个大约3000行的表.它看起来像下面的那个.
Delimited_Col_1 | Delimited_Col_2 | Date
----------------|-----------------|----------
a | x1,x2 | Date-1
b,c | y1,y2,y3 | Date-2
d,e,f | z1,z2 | Date-3
----------------|-----------------|----------
Run Code Online (Sandbox Code Playgroud)
我希望查询结果是Delimited_Col_1和Delimited_Col_2 CSV之间每行的CROSS JOIN的UNION ...如下所示.
Resultant_Col_1 | Resultant_Col_2 | Date
----------------|-----------------|----------
a | x1 | Date-1
a | x2 | Date-1
----------------|-----------------|----------
b | y1 | Date-2
b | y2 | Date-2
b | y3 | Date-2
c | y1 | Date-2
c | y2 | Date-2
c | y3 | Date-2
----------------|-----------------|----------
d | z1 | Date-3
d | z2 | Date-3
e | z1 | Date-3
e | z2 | Date-3
f | z1 | Date-3
f | z2 | Date-3
----------------|-----------------|----------
Run Code Online (Sandbox Code Playgroud)
我该如何实现这一目标?我正在使用SQL Server 2012.
在网上搜索字符串拆分功能(有很多例子).
然后:
select t.date, s1.value, s2.value
from t cross apply
string_split(t.Delimited_Col_1) s1 cross apply
string_split(t.Delimited_Col_2) s2;
Run Code Online (Sandbox Code Playgroud)
这使用了string_split()SQL Server 2016中的功能,但早期版本的功能比比皆是.