简体   繁体   中英

Extract first word from a varchar column and reverse it

I have following data in my table

id nml               
-- ----------------- 
1  Temora sepanil    
2  Human Mixtard     
3  stlliot vergratob 

I need to get the result by extracting first word in column nml and get its last 3 characters with reverse order

That means output should be like

nml               reverse 
----------------- ------- 
Temora sepanil    aro     
Human Mixtard     nam     
stlliot vergratob toi  

You use PostgreSQL's string functions to achieve desired output

in this case am using split_part , right , reverse function

select reverse(right(split_part('Temora sepanil',' ',1),3)) 

output:

aro 

so you can write your query in following format

select nml
      ,reverse(right(split_part(nml,' ',1),3)) "Reverse" 
from tbl
  1. Split nml using regexp_split_to_array(string text, pattern text [, flags text ]) refer Postgres Doc for more info.
  2. Use reverse(str) (refer Postgres Doc ) to reverse the first word form previous split.
  3. Use substr(string, from [, count]) (refer Postgres Doc ) to select first three letters of the reversed test

Query

SELECT 
    nml,
    substr(reverse(regexp_split_to_array(nml, E'\\s+')[0]),3) as reverse
FROM
    MyTable

You can use the SUBSTRING , CHARINDEX , RIGHT and REVERSE function

here's the syntax

  REVERSE(RIGHT(SUBSTRING(nml , 1, CHARINDEX(' ', nml) - 1),3))

sample:

  SELECT REVERSE(RIGHT(SUBSTRING(nml , 1, CHARINDEX(' ', nml) - 1),3)) AS 'Reverse' 
  FROM TableNameHere

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