How to separate two strings separated by a ; into two columns - postgresql

So for example I have this
Fullname
Elen;Morales
Sasha;Karl Wickens
and I want to have this
Firstname Lastname
Elen Morales
Sasha Karl Wickens
Is it possible to do it with regexp_replace?

You can use split_part():
select split_part(fullname, ';', 1) as firstname,
split_part(fullname, ';', 2) as lastname
from the_table;

Related

Trying to extract text using CHARINDEX ()- 1 but getting an error

I have a column with Names, and I am trying to split the column into First and Last Name using Text functions such as LEFT/SUBSTRING/CHARINDEX.
Data in the column:
Name
Yang, Jon
Huang, Eugene
Torres, Ruben
Zhu, Christy
Johnson, Elizabeth
Everything works fine as long as I use this code:
SELECT
[Name]
--,LEFT([Name], CHARINDEX(' ', [Name])) AS FirstName
,SUBSTRING([Name], 1, CHARINDEX(' ', [Name] )) AS FirstName
FROM
DataModeling.Customer
But the problem arises when I try to subtract 1 from CHARINDEX to exclude the Comma from the result and it throws this error:
I have done this operation many times in Excel so trying to replicate it with TSQL. Any suggestion on what I am doing wrong is helpful.
You get that error when CHARINDEX(' ', [Name] ) return 0. So minus 1 will make it negative and it is invalid value for substring()
You can use CASE expression to check the return value from CHARINDEX() and return the correct value to substring()
Or, you can "cheat" by using
CHARINDEX( ' ', [Name] + ' ' )
So CHARINDEX() will always return a value that is more than 0

Union in JPA and using Alias

I have 2 entites, PERSON and PEOPLE
PERSON has columns namely -> FN, LN
PEOPLE has columns -> FIRST, LAST
I want to fetch the union of both the tables together. How do I do it in JPA.
I have used the below way:
Created a new DTO -> Human having 2 fields FIRSTNAME and LASTNAME (case sensitive)
#Query(value=" SELECT FIRSTNAME, LASTNAME FROM "+
"( SELECT "+
" P.FN AS FIRSTNAME, "+
" P.LN AS LASTNAME " +
" FROM PERSON P"+
" UNION "+
" SELECT "+
" A.FIRST AS FIRSTNAME, "+
" A.LAST AS LASTNAME ' +
" FROM PEOPLE A"+
")", nativeQuery = true)
Pageable<Human> getEntireHumanRace() {
....
}
The SQL runs fine, but the ORM always forms a malformed SQL
such as "Syntax error in SQL statement SELECT COUNT(P) FROM PERSON P ...."
InvalidDataAccessResourceUsageException: could not prepare statement
Is there any suggestion on what can be done? Why does it put the count in front of the generated query?
Appreciate in advance.
Why does it put the count in front of the generated query?
Because you are trying to get data with pagination (Pageable). So for total element count Count query executing.
Is there any suggestion on what can be done?
You are using class-based projection and use List<Human>
#Query(value="SELECT FIRSTNAME, LASTNAME FROM ...")
List<Human> getEntireHumanRace();

Set values for all records in a Kdb table based on values of other columns

I need to perform a global update on a KDB table to update two columns. For the FirstName column, I want to remove it's value for records which have empty string in the SecondName column, and for the FullName column I want to replace an encoded delimiter with a space for all rows in the table.
These need not be done in a single update statement if that helps.
update
FirstName:$[SecondName like ""; FirstName; ""],
FullName[FullName; " "; " "]
from table
}
I'm struggling with the syntax - the above is my best attempt but it doesn't work.
One way to achieve that in a sinlge update statement:
q) update FirstName:?[SecondName like ""; SecondName;FirstName], FullName:ssr[;" "; " "]#'FullName from table
For your update for the FirstName you need a ? rather than a $ as the Execution control operator. As it does the execution with a list rather than an atom.
For the FullName you will need to use ssr, which finds where string has "&nbsp" and replaces it with " "
Which would give the following:
q)tab:([]FirstName:("aa";"cc");SecondName:("";"dd");FullName:("aa ";"cc dd"))
q)update FirstName:?[SecondName like ""; count[FirstName]#enlist""; FirstName],FullName:ssr[; " ";" "]each FullName from tab
FirstName SecondName FullName
-----------------------------
"" "" "aa "
"cc" "dd" "cc dd"
Hope this answers your question.
Regards,
Sander
I would recommend to do it in two steps
//create table with mock data
table: ([]FirstName: ("aaa";"ccc"); SecondName: ("bbb";""); FullName: ("aaa bbb";"ccc "));
//step1: set First to "" whenever SecondName is ""
table: update FirstName: (count i)#enlist"" from table where SecondName like "";
//step2: replace spaces in FullName
table: update FullName: ssr[;" ";" "] each FullName from table;
Got it I think:
table:update FirstName:(count i)#enlist "" from table where SecondName like "";
table:update FullName:{ ssr[x; " "; " "] } each FullName from table where FullName like "* *";

Postgresql: Remove hyphens and whitespaces

I am currently working on DB data which contains whitespaces and hyphens. I searched over the net and found this Remove/replace special characters in column values? . I tried to follow the answer but I am still getting hyphens. I tried playing around with it, I can only remove the whitespace
conn_p = p.connect("dbname='p_test' user='postgres' password='postgres' host='localhost'")
conn_t = p.connect("dbname='t_mig1' user='postgres' password='postgres' host='localhost'")
cur_p = conn_p.cursor()
cur_t = conn_t.cursor()
cur_t.execute("SELECT CAST(REGEXP_REPLACE(studentnumber, ' ', '') as integer), firstname, middlename, lastname FROM sprofile")
rows = cur_t.fetchall()
for row in rows:
print "Inserting ", row[0], row[1], row[2], row[3]
cur_p.execute(""" INSERT INTO "a_recipient" (id, first_name, middle_name, last_name) VALUES ('%s', '%s', '%s', '%s') """ % (row[0], row[1], row[2], row[3]))
cur_p.commit()
cur_pl.close()
cur_t.close()
What I would like to achieve is if I got a studentnumber of 001-2012-1456, it will be displayed as 000120121456.
To wipe out all characters in a set efficiently use translate. It takes a set of characters to translate into another set of characters. If the other set is empty it deletes them.
test=> select translate('001-2012-145 6', '- ', '');
translate
-------------
00120121456
While translate is simpler and faster for this particular job, it's important to know how to use regexes for others. To do it with regexp_replace there's two changes you need to make.
First, you have to match the set of - and as [- ].
Then, you have to specify to replace all occurrences, otherwise it will stop after the first one. That's done with the g flag.
test=> select regexp_replace('001-2012-145 6', '[- ]', '', 'g');
regexp_replace
----------------
00120121456
Here's a tutorial on POSIX regular expressions and character sets.
Its very simple to use inbuilt translate function.
Example:
select translate('001-2012-145 6', '- ', '');
Output of above command :
00120121456

TSQL - CONCAT_NULL_YIELDS_NULL ON Not Returning Null?

I have had a look around and seem to have come across a strange issue with SQL Server 2008 R2.
I understand that with CONCAT_NULL_YIELDS_NULL = ON means that the following will always resolve to NULL
SELECT NULL + 'My String'
I'm happy with that, however when using this in conjunction with COALESCE() it doesn’t appear to be working on my database.
Consider the following query where MyString is VARCHAR(2000)
SELECT COALESCE(MyString + ', ', '') FROM MyTableOfValues
Now in my query, when MyString IS NULL it returns an empty (NOT NULL) string. I can see this in the query results window.
However unusually enough, when running this in conjunction with an INSERT it fails to recognise the CONCAT_NULL_YIELDS_NULL instead, inserting a blank ‘, ‘.
Query is as follows for insert.
CONCAT_NULL_YIELDS_NULL ON
INSERT INTO Mytable(StringValue)
SELECT COALESCE(MyString + ', ', '')
FROM MyTableOfValues
Further to this I have also checked the database and CONCAT_NULL_YIELDS_NULL = TRUE…
Use NULLIF(MyString, '') instead of just MyString:
SELECT COALESCE(NULLIF(MyString, '') + ', ', '') FROM MyTableOfValues
Coalesce returns the first nonnull expression among its arguments.
You're getting a ', ' because it's the first nonnull expression in your coalesce call.
http://msdn.microsoft.com/en-us/library/ms190349.aspx
From some of the answers provided I was able to assertain a more in depth understanding of COALESCE().
The reason the above query did not fully work was because although I was checking for nulls, and empty string ('') is not considered null. Therefore although the above query worked, I should have checked for empty strings in my table first.
e.g.
SELECT COALESCE(FirstName + ', ', '') + Surname
FROM
(
SELECT 'Joe' AS Firstname, 'Bloggs' AS Surname UNION ALL
SELECT NULL, 'Jones' UNION ALL
SELECT '', 'Jones' UNION ALL
SELECT 'Bob', 'Tielly'
) AS [MyTable]
Will return
FullName
-----------
Joe, Bloggs
Jones
, Jones
Bob, Tielly
Now row 3 has returned a "," character which I was not originally expecting due to a Blank but NOT NULL value.
The following code now works as expected as it checks for blank values. It works, but it looks like I took the long way around. There may be a better way.
-- Ammended Query
SELECT COALESCE(REPLACE(FirstName, Firstname , Firstname + ', '), '') + Surname AS FullName0
FROM
(
SELECT 'Joe' AS Firstname, 'Bloggs' AS Surname UNION ALL
SELECT NULL, 'Jones' UNION ALL
SELECT '', 'Jones' UNION ALL
SELECT 'Bob', 'Tielly'
) AS [MyTable]