简体   繁体   中英

SQL get text between 2nd last and 3rd last dash

I have some data that looks like this:

20170101 - Wal-Mart #111-1234-5687789-MC000555555

20170101 - Target -1235-56444878 - MC000555555

I want to use a SQL query to get the string between the 2nd last and 3rd last dash, so the results would be.

1234

1235

How can this be accomplished? Since the names of the stores can have dashes, it's not reliable to start counting dashes from the beginning, unless there's some kind of trick I'm unaware of.

Thanks.

 create table test (data varchar(100)); insert into test values ('20170101 - Wal-Mart #111-1234-5687789-MC000555555'), ('20170101 - Target -1235-56444878 - MC000555555'); WITH Rev As ( SELECT REVERSE(data) data FROM test ) , Pos AS ( SELECT data, CHARINDEX('-', data, CHARINDEX('-', data, 0) + 1) + 1 AS PIni, CHARINDEX('-', data, CHARINDEX('-', data, CHARINDEX('-', data, 0)+1)+1) AS PFin FROM Rev ) SELECT REVERSE(SUBSTRING(data, PIni, PFin - PIni)) FROM Pos; GO 
\n|  (No column name) | \n|  :--------------- | \n|  1234 | \n|  1235 | \n

dbfiddle here

I am not sure how else would you approach this, unless you count dashes. Since you cannot start counting from the beginning of the string (because of the names of the stores), maybe you can count from the end. So a combination of the following should do the thing for you:

  • SQL reverse - reverses the string (so you can "count from the end")
  • SQL charindex - gets the index of a given char in a given string
  • SQL substring - so you can extract the needed data, once you know where the second last and third last dashes are

Hope this helps, cheers.

You can nest one SUBSTRING_INDEX() inside another, like this:

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(data,'-',-3),'-',1) FROM `test`

This will extract the last three "portions", then extract the first "portion" from that.

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