简体   繁体   中英

How do I convert table column data from 'LastName, FirstName' to 'FirstName LastName' in Postgres

How do I convert table column data from 'LastName, FirstName' to 'FirstName LastName' in Postgres.

So if the table column contains 'Ona, Lisa' I want it to return 'Lisa Ona'. If the column doesnt contain a ' ,' then I want it to return null. I've been trying to use postgres functions SUBSTRING and REGEXP_REPLACE but cannot get anything working.

You need strpos and substr functions and a CASE to return NULL .

SELECT CASE WHEN strpos(name,', ') > 0 
            THEN substr(name,strpos(name,', ') + 2)  ||' ' || substr(name,0, strpos(name,', '))
            ELSE NULL END
    FROM person

fiddle

Nevermind worked out a solution using SPLIT_PART function

SELECT 
t1.sort_name,
split_part(t1.sort_name, ', ', 2)|| ' ' || split_part(t1.sort_name, ', ', 1)  
FROM artist t1
WHERE 
t1.sort_name LIKE '%, %'

try this

select split_part(name,',',2) ||' '|| split_part(name,',',1) as "thename" from tblname     
where name LIKE '%,%'

String Functions and Operators and PostgreSQL SPLIT PART

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