ID NAME COMMENTS
1 ABC HI
2,3 DEF,GHI HELLO
4 JKL HII
5,6,7 M,N,O HEY
Run Code Online (Sandbox Code Playgroud)
我在上面提到的数据中使用逗号分隔值,这些逗号分隔值按顺序映射.对于Eg.id 1与ABC相关,2与DEF相关,3与GHI相关,依此类推.
我想使用sql查询来获得以下输出:
ID NAME COMMENTS
1 ABC HI
2 DEF HELLO
3 GHI HELLO
4 JKL HII
5 M HEY
6 N HEY
7 O HEY
Run Code Online (Sandbox Code Playgroud)
在SQL Server 2016+中,您可以使用string_split().
在SQL Server 2016之前,您需要一些其他方法来拆分字符串.使用Jeff Moden的CSV Splitter表值函数:
select
id = i.item
, name = n.item
, comments = t.comments
from t
cross apply dbo.delimitedsplit8k(t.id,',') i
cross apply dbo.delimitedsplit8k(t.name,',') n
where i.itemnumber = n.itemnumber
Run Code Online (Sandbox Code Playgroud)
rextester 演示:http://rextester.com/EEFRS3810
收益:
+----+------+----------+
| id | name | comments |
+----+------+----------+
| 1 | ABC | HI |
| 2 | DEF | HELLO |
| 3 | GHI | HELLO |
| 4 | JKL | HII |
| 5 | M | HEY |
| 6 | N | HEY |
| 7 | O | HEY |
+----+------+----------+
Run Code Online (Sandbox Code Playgroud)
拆分字符串参考:
string_split() 在SQL Server 2016中:后续#1 - Aaron Bertrand使用John Cappelletti的内联xml字符串拆分器:
select
id = i.RetVal
, name = n.RetVal
, comments = t.comments
from t
Cross Apply (
Select RetSeq = Row_Number() over (Order By (Select null))
,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
From (Select x = Cast('<x>' + replace((Select replace(t.[Id],',','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as x
Cross Apply x.nodes('x') AS B(i)
) i
Cross Apply (
Select RetSeq = Row_Number() over (Order By (Select null))
,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
From (Select x = Cast('<x>' + replace((Select replace(t.[Name],',','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as x
Cross Apply x.nodes('x') AS B(i)
) n
where i.RetSeq = n.RetSeq
Run Code Online (Sandbox Code Playgroud)
rextester演示:http://rextester.com/ZCKVNV72753