简体   繁体   中英

Extracting Multiple Numerical Values from Text

048(70F-Y),045(DDI-Y),454(CMDE-Y)

I have the above data in a column field, I need to extract each number before the, so in the above example I would want to see 048, 045, 454.

Note the data in the field will change in each record in the above you have 3 sets of numbers. Sometimes you may have just one set or 6 sets. I just need to capture all sets of numbers that are to the left of the ( .

Ideally I would want the results to show in a new column like below. I have tried a few things and gotten no where any help would be greatly appreciate.

I would expect the result to look like the below:

+----------+-----------------------------------+---------------+
| EventId  |            PAEditTypes            |     Edits     |
+----------+-----------------------------------+---------------+
|  6929107 | 082(SPA-Y),177(QL-Y)              |      082, 177 |
| 26534980 | 048(70F-Y),045(DDI-Y),454(CMDE-Y) | 045, 048, 454 |
+----------+-----------------------------------+---------------+

You can get desired output with the following step:

  1. use string_split with cross apply to isolate each item
  2. use left to get only the first part of each item together with CHARINDEX to know where you have to stop
  3. use STRING_AGG to build the final result, adding WITHIN GROUP clause to enforce ordering (if ordering is not important just remove WITHIN GROUP clause)

This is a TSQL sample that should work:

declare @tmp table ( EventId  varchar(50), PAEditTypes varchar(200) )

insert into @tmp values
     ('6929107' ,'082(SPA-Y),177(QL-Y)'             ) 
    ,('26534980','048(70F-Y),045(DDI-Y),454(CMDE-Y)') 

select 
     EventId
   , PAEditTypes
   , STRING_AGG(left(value,CHARINDEX('(',value)-1),', ') WITHIN GROUP (ORDER BY value ASC) as Edits
from 
    @tmp
        cross apply 
    string_split(PAEditTypes, ',')
group by 
      EventId
    , PAEditTypes
order by
    EventId desc

Output:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM