【问题标题】:SQL Server : extract strings from delimiterSQL Server:从分隔符中提取字符串
【发布时间】:2021-11-22 16:35:46
【问题描述】:

我正在查询一个名为 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

有什么想法可以将剩余的两个部分分成单独的列(即文档类型和参考)?

非常感谢

【问题讨论】:

    标签: sql-server substring


    【解决方案1】:

    必须有数百种方法来进行这种字符串操作,这里有几种。

    这使用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
    

    【讨论】:

    • 嗨,谢谢。请您告诉我如何将其合并到我现有的选择语句中,并使用该查询引用列?
    • @NiteHawk - 现有的选择语句是什么?除了我假设在上述查询中的表 MyTable 中的示例数据之外,您的问题中没有任何内容。
    • 嗨,谢谢。对不起,我想通了。我使用这个 Youtube 视频来帮助在我现有的查询 youtube.com/watch?v=5KGjqnMss7g 中使用 with 语句来解决这个问题。最后一个问题,你知道为什么有些字符串没有用“-”分隔符分割吗?也由于某种原因,部分电子邮件被拆分(例如 uk.eu@XXXXX.com)![](ibb.co/LtT0wCn)非常感谢您的帮助!非常感谢
    • @NiteHawk 这似乎与所问的问题不同,当然需要查看您的特定数据;上面回答了所提出的问题。无论如何发布另一个具体问题,但请考虑what to do when someone answers your question
    猜你喜欢
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    • 2016-11-24
    相关资源
    最近更新 更多