SQL 服务器:从定界符中提取字符串
SQL Server : extract strings from delimiter
我正在查询一个名为 Description 的列,我需要从每个“-”分隔符中提取字符串;
例如
Description
---------------------------------
abc@abc.com - Invoice - A12222203
FGH@fgh.com - Credit - C12222333
所以理想情况下需要将每个段提取到三个单独的列中;
例如
Email | Doc Type | Ref
------------+----------+----------
abc@abc.com | Invoice | A12222203
FGH@fgh.com | Credit | C12222333
我已经使用
提取了电子邮件地址
Substring(SL_Reference,0,charindex('-',SL_Reference))Email
有什么想法可以将剩余的两个部分拆分成单独的列(即文档类型和参考)吗?
非常感谢
一定有数百种方法可以执行此字符串操作,这里有两种。
这使用 apply
来获取每个分隔符的位置,然后简单的字符串操作来获取每个部分。
with myTable as (
select * from (values('abc@abc.com - Invoice - A12222203'),('FGH@fgh.com - Credit - C12222333'))v(Description)
)
select
Trim(Left(description,h1-1)) Email,
Trim(Substring(description,h1+1,Len(description)-h2-h1-1)) DocType,
Trim(Right(description,h2-1)) Ref
from mytable
cross apply(values(CharIndex('-',description)))v1(h1)
cross apply(values(CharIndex('-',Reverse(description))))v2(h2)
这会将字符串拆分为多行,然后有条件地聚合回一行。
with myTable as (
select * from (values('abc@abc.com - Invoice - A12222203'),('FGH@fgh.com - Credit - C12222333'))v(Description)
)
select
max(Iif(rn=1,v,null)) Email,
max(Iif(rn=2,v,null)) Doctype,
max(Iif(rn=3,v,null)) Ref
from mytable
cross apply (
select Trim(value)v,row_number() over(order by (select null)) rn
from String_Split(Description,'-')
)s
group by Description
我正在查询一个名为 Description 的列,我需要从每个“-”分隔符中提取字符串;
例如
Description
---------------------------------
abc@abc.com - Invoice - A12222203
FGH@fgh.com - Credit - C12222333
所以理想情况下需要将每个段提取到三个单独的列中;
例如
Email | Doc Type | Ref
------------+----------+----------
abc@abc.com | Invoice | A12222203
FGH@fgh.com | Credit | C12222333
我已经使用
提取了电子邮件地址Substring(SL_Reference,0,charindex('-',SL_Reference))Email
有什么想法可以将剩余的两个部分拆分成单独的列(即文档类型和参考)吗?
非常感谢
一定有数百种方法可以执行此字符串操作,这里有两种。
这使用 apply
来获取每个分隔符的位置,然后简单的字符串操作来获取每个部分。
with myTable as (
select * from (values('abc@abc.com - Invoice - A12222203'),('FGH@fgh.com - Credit - C12222333'))v(Description)
)
select
Trim(Left(description,h1-1)) Email,
Trim(Substring(description,h1+1,Len(description)-h2-h1-1)) DocType,
Trim(Right(description,h2-1)) Ref
from mytable
cross apply(values(CharIndex('-',description)))v1(h1)
cross apply(values(CharIndex('-',Reverse(description))))v2(h2)
这会将字符串拆分为多行,然后有条件地聚合回一行。
with myTable as (
select * from (values('abc@abc.com - Invoice - A12222203'),('FGH@fgh.com - Credit - C12222333'))v(Description)
)
select
max(Iif(rn=1,v,null)) Email,
max(Iif(rn=2,v,null)) Doctype,
max(Iif(rn=3,v,null)) Ref
from mytable
cross apply (
select Trim(value)v,row_number() over(order by (select null)) rn
from String_Split(Description,'-')
)s
group by Description