Splitting string based on only a specific delimiter - mysql

I'm trying to split a field (at some delimiter ';') and insert the results into a table.
The maximum is 5 substrings delimited by ';' . There will only be a maximum of 5 fruits.
Given only the fruit column, how can I split the string to get the separate fruits. If there are lesser fruits than 5, remaining columns will return NA.
fruits
fruit1
fruit2
fruit3
fruit4
fruit5
apple; orange; banana
apple
orange
banana
-null-
-null-
apple; orange; pine-apple; dragon-fruit; banana
apple
orange
pine-apple
dragon-fruit
banana
pear/grape ; orange; banana; strawberry
pear/grape
orange
banana
strawberry
-null-
apple; blueberry; kiwi/lemon
apple
blueberry
kiwi/lemon
-null-
-null-
I 1st created new columns and set it all to null.
I have tried the following code but it does not work, if there are less fruits than columns, the remaining columns will just take the values of the last fruit instead of null.
SELECT
fruits,
SUBSTRING_INDEX(fruits, ';', 1) AS 'fruit1',
CASE
WHEN LOCATE(';', fruits, LENGTH(fruit1)+1) = 0 THEN NULL
ELSE SUBSTRING_INDEX(SUBSTRING_INDEX(fruits, ';', 2), ';', -1)
END AS 'fruit2',
CASE
WHEN LOCATE(';', fruits, LENGTH(fruit1)+LENGTH(fruit2)+1) = 0 THEN NULL
WHEN LOCATE(';', fruits, (LOCATE(';', fruits, LENGTH(fruit1)) + 2)) = 0 THEN NULL
ELSE SUBSTRING_INDEX(SUBSTRING_INDEX(fruits, ';', 3), ';', -1)
END AS 'fruit3',
CASE
WHEN LOCATE(';', fruits, LENGTH(fruit1) + LENGTH(fruit2) + LENGTH(fruit3) + 3) = 0 THEN NULL
WHEN LOCATE(';', fruits, (LOCATE(';', fruits, LENGTH(fruit1) + LENGTH(fruit2) + LENGTH(fruit3)+2) + 1)) = 0 THEN NULL
ELSE SUBSTRING_INDEX(SUBSTRING_INDEX(fruits, ';', 4), ';', -1)
END AS 'fruit4'
FROM TABLENAME;
Is there any more information to split the string?

In MySQL 5.7 and 8.0, JSON functions are now supported. You could do some string-manipulation to turn this:
apple; orange; banana
into this:
["apple", "orange", "banana"]
Then use JSON functions to extract a specific array element by position.
mysql> set #s = 'apple; orange; banana';
mysql> select cast(concat('["', replace(#s, '; ', '","'), '"]') as json) as array;
+-------------------------------+
| array |
+-------------------------------+
| ["apple", "orange", "banana"] |
+-------------------------------+
mysql> select json_unquote(json_extract(
cast(concat('["', replace(#s, '; ', '","'), '"]') as json),
'$[1]')) as element;
+---------+
| element |
+---------+
| orange |
+---------+
Then you can extract '$[2]' or '$[3]' or any other element. You could use the ->> shortcut for extract-and-unquote.
SELECT
fruits,
fruits->>'$[0]' AS `fruit1`,
fruits->>'$[1]' AS `fruit2`,
fruits->>'$[2]' AS `fruit3`,
fruits->>'$[3]' AS `fruit4`
FROM (
SELECT CAST(CONCAT('["', REPLACE(fruits, '; ', '","'), '"]')) AS fruits
FROM TABLENAME
) AS f;
You might consider storing the list as a JSON columns, instead of your current semicolon-separated string format.

Related

Convert JSON string in to separate fields

I have a table with two columns:
create table customerData (id bigint IDENTITY(1,1) NOT NULL, rawData varchar(max))
here the rawData will save the json format data in string, for example below will be the data in that column:
insert into customerData
values ('[{"customerName":"K C Nalina","attendance":"P","collectedAmount":"757","isOverdrafted":false,"loanDisbProduct":null,"paidBy":"Y","customerNumber":"1917889","totalDue":"757"},{"customerName":"Mahalakshmi","attendance":"P","collectedAmount":"881","isOverdrafted":false,"loanDisbProduct":"Emergency Loan","paidBy":"Y","customerNumber":"430833","totalDue":"757"}]'),
('[{"customerName":"John","attendance":"P","collectedAmount":"700","isOverdrafted":false,"loanDisbProduct":null,"paidBy":"Y","customerNumber":"192222","totalDue":"788"},{"customerName":"weldon","attendance":"P","collectedAmount":"771","isOverdrafted":false,"loanDisbProduct":"Emergency Loan","paidBy":"Y","customerNumber":"435874","totalDue":"757"}]')
Expected result :
I need these customerName, customerNumber, loanDisbProduct to be shown in separate fields for each rows.
Also to note the customer details inside rawData for each row will be more than two in many cases.
I don't know how to shred the data inside rawData column.
And I'm using SQL server 2012 and it doesn't support JSON data so I have to manipulate the string and get the field.
Thanks to Red-Gate blog post, first define a View as follow:(I will use this view to generate a new uniqueidentifier inside the function)
CREATE VIEW getNewID as SELECT NEWID() AS new_id
Then create a function as follow(This function is same as the one in Red-Gate blog post, but I have changed it a little a bit and include the identifier in it):
CREATE FUNCTION dbo.parseJSON( #JSON NVARCHAR(MAX))
RETURNS #hierarchy TABLE
(
Element_ID INT IDENTITY(1, 1) NOT NULL, /* internal surrogate primary key gives the order of parsing and the list order */
SequenceNo [int] NULL, /* the place in the sequence for the element */
Parent_ID INT null, /* if the element has a parent then it is in this column. The document is the ultimate parent, so you can get the structure from recursing from the document */
Object_ID INT null, /* each list or object has an object id. This ties all elements to a parent. Lists are treated as objects here */
Name NVARCHAR(2000) NULL, /* the Name of the object */
StringValue NVARCHAR(MAX) NOT NULL,/*the string representation of the value of the element. */
ValueType VARCHAR(10) NOT NULL, /* the declared type of the value represented as a string in StringValue*/
Identifier UNIQUEIDENTIFIER NOT NULL
)
AS
BEGIN
DECLARE
#FirstObject INT, --the index of the first open bracket found in the JSON string
#OpenDelimiter INT,--the index of the next open bracket found in the JSON string
#NextOpenDelimiter INT,--the index of subsequent open bracket found in the JSON string
#NextCloseDelimiter INT,--the index of subsequent close bracket found in the JSON string
#Type NVARCHAR(10),--whether it denotes an object or an array
#NextCloseDelimiterChar CHAR(1),--either a '}' or a ']'
#Contents NVARCHAR(MAX), --the unparsed contents of the bracketed expression
#Start INT, --index of the start of the token that you are parsing
#end INT,--index of the end of the token that you are parsing
#param INT,--the parameter at the end of the next Object/Array token
#EndOfName INT,--the index of the start of the parameter at end of Object/Array token
#token NVARCHAR(200),--either a string or object
#value NVARCHAR(MAX), -- the value as a string
#SequenceNo int, -- the sequence number within a list
#Name NVARCHAR(200), --the Name as a string
#Parent_ID INT,--the next parent ID to allocate
#lenJSON INT,--the current length of the JSON String
#characters NCHAR(36),--used to convert hex to decimal
#result BIGINT,--the value of the hex symbol being parsed
#index SMALLINT,--used for parsing the hex value
#Escape INT,--the index of the next escape character
#Identifier UNIQUEIDENTIFIER
DECLARE #Strings TABLE /* in this temporary table we keep all strings, even the Names of the elements, since they are 'escaped' in a different way, and may contain, unescaped, brackets denoting objects or lists. These are replaced in the JSON string by tokens representing the string */
(
String_ID INT IDENTITY(1, 1),
StringValue NVARCHAR(MAX)
)
SELECT--initialise the characters to convert hex to ascii
#characters='0123456789abcdefghijklmnopqrstuvwxyz',
#SequenceNo=0, --set the sequence no. to something sensible.
/* firstly we process all strings. This is done because [{} and ] aren't escaped in strings, which complicates an iterative parse. */
#Parent_ID=0,
#Identifier = (SELECT new_id FROM dbo.getNewID)
WHILE 1=1 --forever until there is nothing more to do
BEGIN
SELECT
#start=PATINDEX('%[^a-zA-Z]["]%', #json collate SQL_Latin1_General_CP850_Bin);--next delimited string
IF #start=0 BREAK --no more so drop through the WHILE loop
IF SUBSTRING(#json, #start+1, 1)='"'
BEGIN --Delimited Name
SET #start=#Start+1;
SET #end=PATINDEX('%[^\]["]%', RIGHT(#json, LEN(#json+'|')-#start) collate SQL_Latin1_General_CP850_Bin);
END
IF #end=0 --either the end or no end delimiter to last string
BEGIN-- check if ending with a double slash...
SET #end=PATINDEX('%[\][\]["]%', RIGHT(#json, LEN(#json+'|')-#start) collate SQL_Latin1_General_CP850_Bin);
IF #end=0 --we really have reached the end
BEGIN
BREAK --assume all tokens found
END
END
SELECT #token=SUBSTRING(#json, #start+1, #end-1)
--now put in the escaped control characters
SELECT #token=REPLACE(#token, FromString, ToString)
FROM
(SELECT '\b', CHAR(08)
UNION ALL SELECT '\f', CHAR(12)
UNION ALL SELECT '\n', CHAR(10)
UNION ALL SELECT '\r', CHAR(13)
UNION ALL SELECT '\t', CHAR(09)
UNION ALL SELECT '\"', '"'
UNION ALL SELECT '\/', '/'
) substitutions(FromString, ToString)
SELECT #token=Replace(#token, '\\', '\')
SELECT #result=0, #escape=1
--Begin to take out any hex escape codes
WHILE #escape>0
BEGIN
SELECT #index=0,
--find the next hex escape sequence
#escape=PATINDEX('%\x[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%', #token collate SQL_Latin1_General_CP850_Bin)
IF #escape>0 --if there is one
BEGIN
WHILE #index<4 --there are always four digits to a \x sequence
BEGIN
SELECT --determine its value
#result=#result+POWER(16, #index)
*(CHARINDEX(SUBSTRING(#token, #escape+2+3-#index, 1),
#characters)-1), #index=#index+1 ;
END
-- and replace the hex sequence by its unicode value
SELECT #token=STUFF(#token, #escape, 6, NCHAR(#result))
END
END
--now store the string away
INSERT INTO #Strings (StringValue) SELECT #token
-- and replace the string with a token
SELECT #JSON=STUFF(#json, #start, #end+1,
'#string'+CONVERT(NCHAR(5), ##identity))
END
-- all strings are now removed. Now we find the first leaf.
WHILE 1=1 --forever until there is nothing more to do
BEGIN
SELECT #Parent_ID=#Parent_ID+1, #Identifier=(SELECT new_id FROM dbo.getNewID)
--find the first object or list by looking for the open bracket
SELECT #FirstObject=PATINDEX('%[{[[]%', #json collate SQL_Latin1_General_CP850_Bin)--object or array
IF #FirstObject = 0 BREAK
IF (SUBSTRING(#json, #FirstObject, 1)='{')
SELECT #NextCloseDelimiterChar='}', #type='object'
ELSE
SELECT #NextCloseDelimiterChar=']', #type='array'
SELECT #OpenDelimiter=#firstObject
WHILE 1=1 --find the innermost object or list...
BEGIN
SELECT
#lenJSON=LEN(#JSON+'|')-1
--find the matching close-delimiter proceeding after the open-delimiter
SELECT
#NextCloseDelimiter=CHARINDEX(#NextCloseDelimiterChar, #json,
#OpenDelimiter+1)
--is there an intervening open-delimiter of either type
SELECT #NextOpenDelimiter=PATINDEX('%[{[[]%',
RIGHT(#json, #lenJSON-#OpenDelimiter)collate SQL_Latin1_General_CP850_Bin)--object
IF #NextOpenDelimiter=0
BREAK
SELECT #NextOpenDelimiter=#NextOpenDelimiter+#OpenDelimiter
IF #NextCloseDelimiter<#NextOpenDelimiter
BREAK
IF SUBSTRING(#json, #NextOpenDelimiter, 1)='{'
SELECT #NextCloseDelimiterChar='}', #type='object'
ELSE
SELECT #NextCloseDelimiterChar=']', #type='array'
SELECT #OpenDelimiter=#NextOpenDelimiter
END
---and parse out the list or Name/value pairs
SELECT
#contents=SUBSTRING(#json, #OpenDelimiter+1,
#NextCloseDelimiter-#OpenDelimiter-1)
SELECT
#JSON=STUFF(#json, #OpenDelimiter,
#NextCloseDelimiter-#OpenDelimiter+1,
'#'+#type+CONVERT(NCHAR(5), #Parent_ID))
WHILE (PATINDEX('%[A-Za-z0-9#+.e]%', #contents collate SQL_Latin1_General_CP850_Bin))<>0
BEGIN
IF #Type='object' --it will be a 0-n list containing a string followed by a string, number,boolean, or null
BEGIN
SELECT
#SequenceNo=0,#end=CHARINDEX(':', ' '+#contents)--if there is anything, it will be a string-based Name.
SELECT #start=PATINDEX('%[^A-Za-z#][#]%', ' '+#contents collate SQL_Latin1_General_CP850_Bin)--AAAAAAAA
SELECT #token=RTrim(Substring(' '+#contents, #start+1, #End-#Start-1)),
#endofName=PATINDEX('%[0-9]%', #token collate SQL_Latin1_General_CP850_Bin),
#param=RIGHT(#token, LEN(#token)-#endofName+1)
SELECT
#token=LEFT(#token, #endofName-1),
#Contents=RIGHT(' '+#contents, LEN(' '+#contents+'|')-#end-1)
SELECT #Name=StringValue FROM #strings
WHERE string_id=#param --fetch the Name
END
ELSE
SELECT #Name=null,#SequenceNo=#SequenceNo+1
SELECT
#end=CHARINDEX(',', #contents)-- a string-token, object-token, list-token, number,boolean, or null
IF #end=0
--HR Engineering notation bugfix start
IF ISNUMERIC(#contents) = 1
SELECT #end = LEN(#contents) + 1
Else
--HR Engineering notation bugfix end
SELECT #end=PATINDEX('%[A-Za-z0-9#+.e][^A-Za-z0-9#+.e]%', #contents+' ' collate SQL_Latin1_General_CP850_Bin) + 1
SELECT
#start=PATINDEX('%[^A-Za-z0-9#+.e][A-Za-z0-9#+.e]%', ' '+#contents collate SQL_Latin1_General_CP850_Bin)
--select #start,#end, LEN(#contents+'|'), #contents
SELECT
#Value=RTRIM(SUBSTRING(#contents, #start, #End-#Start)),
#Contents=RIGHT(#contents+' ', LEN(#contents+'|')-#end)
IF SUBSTRING(#value, 1, 7)='#object'
INSERT INTO #hierarchy
(Name, SequenceNo, Parent_ID, StringValue, Object_ID, ValueType, Identifier)
SELECT #Name, #SequenceNo, #Parent_ID, SUBSTRING(#value, 8, 5),
SUBSTRING(#value, 8, 5), 'object' , #Identifier
ELSE
IF SUBSTRING(#value, 1, 6)='#array'
INSERT INTO #hierarchy
(Name, SequenceNo, Parent_ID, StringValue, Object_ID, ValueType, Identifier)
SELECT #Name, #SequenceNo, #Parent_ID, SUBSTRING(#value, 7, 5),
SUBSTRING(#value, 7, 5), 'array' , #Identifier
ELSE
IF SUBSTRING(#value, 1, 7)='#string'
INSERT INTO #hierarchy
(Name, SequenceNo, Parent_ID, StringValue, ValueType, Identifier)
SELECT #Name, #SequenceNo, #Parent_ID, StringValue, 'string', #Identifier
FROM #strings
WHERE string_id=SUBSTRING(#value, 8, 5)
ELSE
IF #value IN ('true', 'false')
INSERT INTO #hierarchy
(Name, SequenceNo, Parent_ID, StringValue, ValueType, Identifier)
SELECT #Name, #SequenceNo, #Parent_ID, #value, 'boolean', #Identifier
ELSE
IF #value='null'
INSERT INTO #hierarchy
(Name, SequenceNo, Parent_ID, StringValue, ValueType, Identifier)
SELECT #Name, #SequenceNo, #Parent_ID, #value, 'null', #Identifier
ELSE
IF PATINDEX('%[^0-9]%', #value collate SQL_Latin1_General_CP850_Bin)>0
INSERT INTO #hierarchy
(Name, SequenceNo, Parent_ID, StringValue, ValueType,Identifier)
SELECT #Name, #SequenceNo, #Parent_ID, #value, 'real', #Identifier
ELSE
INSERT INTO #hierarchy
(Name, SequenceNo, Parent_ID, StringValue, ValueType, Identifier)
SELECT #Name, #SequenceNo, #Parent_ID, #value, 'int', #Identifier
if #Contents=' ' Select #SequenceNo=0
END
END
INSERT INTO #hierarchy (Name, SequenceNo, Parent_ID, StringValue, Object_ID, ValueType, Identifier)
SELECT '-',1, NULL, '', #Parent_ID-1, #type, #Identifier
--
RETURN
END
Finally, If we have this table and data:
DECLARE #customerData TABLE (jsonValue NVARCHAR(MAX))
INSERT INTO #customerData
VALUES ('[{"customerName":"K C Nalina","attendance":"P","collectedAmount":"757","isOverdrafted":false,"loanDisbProduct":null,"paidBy":"Y","customerNumber":"1917889","totalDue":"757"},{"customerName":"Mahalakshmi","attendance":"P","collectedAmount":"881","isOverdrafted":false,"loanDisbProduct":"Emergency Loan","paidBy":"Y","customerNumber":"430833","totalDue":"757"}]'),
('[{"customerName":"John","attendance":"P","collectedAmount":"700", "isOverdrafted":false,"loanDisbProduct":null,"paidBy":"Y","customerNumber":"192222","totalDue":"788"},{"customerName":"weldon","attendance":"P","collectedAmount":"771","isOverdrafted":false,"loanDisbProduct":"Emergency Loan","paidBy":"Y","customerNumber":"435874","totalDue":"757"}]')
We can simply parse the JSON value as below:
;WITH jsonValue AS(
SELECT * FROM #customerData
CROSS APPLY(SELECT * FROM dbo.parseJSON(jsonvalue)) AS d
WHERE d.Name IN('customerName', 'customerNumber', 'loanDisbProduct')
)
,openResult AS(
SELECT i.Name, i.StringValue, i.Identifier FROM jsonValue AS i
)
SELECT
MAX(K.CustomerName) AS CustomerName,
MAX(K.CustomerNumber) AS CustomerNumber,
MAX(K.LoanDisbProduct) AS LoanDisbProduct
FROM (
SELECT
CASE WHEN openResult.Name='customerName' THEN openResult.StringValue ELSE NULL END AS CustomerName,
CASE WHEN openResult.Name='customerNumber' THEN openResult.StringValue ELSE NULL END AS CustomerNumber,
CASE WHEN openResult.Name='loanDisbProduct' THEN openResult.StringValue ELSE NULL END AS LoanDisbProduct,
openResult.Identifier
FROM openResult
) AS K
GROUP BY K.Identifier
And we will get the following output:
CustomerName | CustomerNumber | LoanDisbProduct
------------------------------------------------------
John | 192222 | null
Mahalakshmi | 430833 | Emergency Loan
K C Nalina | 1917889 | null
weldon | 435874 | Emergency Loan
If you do not know how many customers for each row, you shouldn't shred each customer to one field, at least a row pr customer.
Here is a start on shredding the data, I am using the dbo.STRING_SPLIT function from this page:
First I split by {} in the Json, then I split by ',', and then You ave the attribute name and value for each ID, with numbering of the customers in each row.
I could have split on ',' the same way as for '{...}' however I chose to use a function for this.
Everything is reliant on the same structure of the JSON. To do better parsing SQL server 2016+ would be recommended.
DROP TABLE IF EXISTS #customerData
create table #customerData (id bigint IDENTITY(1,1) NOT NULL, rawData varchar(max))
INSERT INTO #customerData
VALUES ('[{"customerName":"K C Nalina","attendance":"P","collectedAmount":"757","isOverdrafted":false,"loanDisbProduct":null,"paidBy":"Y","customerNumber":"1917889","totalDue":"757"},{"customerName":"Mahalakshmi","attendance":"P","collectedAmount":"881","isOverdrafted":false,"loanDisbProduct":"Emergency Loan","paidBy":"Y","customerNumber":"430833","totalDue":"757"}]'),
('[{"customerName":"John","attendance":"P","collectedAmount":"700","isOverdrafted":false,"loanDisbProduct":null,"paidBy":"Y","customerNumber":"192222","totalDue":"788"},{"customerName":"weldon","attendance":"P","collectedAmount":"771","isOverdrafted":false,"loanDisbProduct":"Emergency Loan","paidBy":"Y","customerNumber":"435874","totalDue":"757"}]')
;
WITH cte AS
(
SELECT id
, REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING(rawData, CHARINDEX('{', rawData), CHARINDEX('}', rawData) - CHARINDEX('{', rawData)), '{', ''), '[', ''), '}', ''), ']', '') person
, SUBSTRING(rawData, CHARINDEX('}', rawData) + 1, LEN(rawData)) personrest
, 1 nr
FROM #customerData
UNION ALL
SELECT id
, REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING(personrest, CHARINDEX('{', personrest), CHARINDEX('}', personrest) - CHARINDEX('{', personrest)), '{', ''), '[', ''), '}', ''), ']', '')
, SUBSTRING(personrest, CHARINDEX('}', personrest) + 1, LEN(personrest)) personrest
, nr + 1
FROM cte
WHERE CHARINDEX('}', personrest) > 0
AND CHARINDEX('{', personrest) > 0
)
SELECT id
, a.nr CustomerOrder
, LEFT([value], CHARINDEX(':', [value]) - 1)
, SUBSTRING([value], CHARINDEX(':', [value]) + 1, LEN([value]))
FROM cte a
CROSS APPLY (
SELECT *
FROM dbo.STRING_SPLIT(REPLACE(a.person, '"', ''), ',')
) b
The result is:
+─────+────────────────+──────────────────+─────────────────+
| id | CustomerOrder | Attribute | value |
+─────+────────────────+──────────────────+─────────────────+
| 1 | 1 | customerName | K C Nalina |
| 1 | 1 | attendance | P |
| 1 | 1 | collectedAmount | 757 |
| 1 | 1 | isOverdrafted | false |
| 1 | 1 | loanDisbProduct | null |
| 1 | 1 | paidBy | Y |
| 1 | 1 | customerNumber | 1917889 |
| 1 | 1 | totalDue | 757 |
| 2 | 1 | customerName | John |
| 2 | 1 | attendance | P |
| 2 | 1 | collectedAmount | 700 |
| 2 | 1 | isOverdrafted | false |
| 2 | 1 | loanDisbProduct | null |
| 2 | 1 | paidBy | Y |
| 2 | 1 | customerNumber | 192222 |
| 2 | 1 | totalDue | 788 |
| 2 | 2 | customerName | weldon |
| 2 | 2 | attendance | P |
| 2 | 2 | collectedAmount | 771 |
| 2 | 2 | isOverdrafted | false |
| 2 | 2 | loanDisbProduct | Emergency Loan |
| 2 | 2 | paidBy | Y |
| 2 | 2 | customerNumber | 435874 |
| 2 | 2 | totalDue | 757 |
| 1 | 2 | customerName | Mahalakshmi |
| 1 | 2 | attendance | P |
| 1 | 2 | collectedAmount | 881 |
| 1 | 2 | isOverdrafted | false |
| 1 | 2 | loanDisbProduct | Emergency Loan |
| 1 | 2 | paidBy | Y |
| 1 | 2 | customerNumber | 430833 |
| 1 | 2 | totalDue | 757 |
+─────+────────────────+──────────────────+─────────────────+
Best was to upgrade to v2016+. With JSON support this was easy...
On v2012 you have to hack around. It might be a better choice to use another tool for this. But, if you have to stick to TSQL, I would try to transform the JSON to attribute centered XML like here:
DECLARE #customerData TABLE (id bigint IDENTITY(1,1) NOT NULL, rawData varchar(max));
insert into #customerData
values ('[{"customerName":"K C Nalina","attendance":"P","collectedAmount":"757","isOverdrafted":false,"loanDisbProduct":null,"paidBy":"Y","customerNumber":"1917889","totalDue":"757"},{"customerName":"Mahalakshmi","attendance":"P","collectedAmount":"881","isOverdrafted":false,"loanDisbProduct":"Emergency Loan","paidBy":"Y","customerNumber":"430833","totalDue":"757"}]'),
('[{"customerName":"John","attendance":"P","collectedAmount":"700","isOverdrafted":false,"loanDisbProduct":null,"paidBy":"Y","customerNumber":"192222","totalDue":"788"},{"customerName":"weldon","attendance":"P","collectedAmount":"771","isOverdrafted":false,"loanDisbProduct":"Emergency Loan","paidBy":"Y","customerNumber":"435874","totalDue":"757"}]')
--the query
SELECT cd.id
,B.*
FROM #customerData cd
CROSS APPLY(SELECT REPLACE(REPLACE(REPLACE(cd.rawData,'false','"0"'),'true','"1"'),'null','"#NULL"')) A(JustStringValues)
CROSS APPLY(SELECT CAST(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(JustStringValues,'[',''),']',''),'},{"',' /><x '),'{"','<x '),'}',' />'),'","','" '),'":"','="') AS XML)) B(SinlgeRow)
--the result
<x customerName="K C Nalina" attendance="P" collectedAmount="757" isOverdrafted="0" loanDisbProduct="#NULL" paidBy="Y" customerNumber="1917889" totalDue="757" /x>
<x customerName="Mahalakshmi" attendance="P" collectedAmount="881" isOverdrafted="0" loanDisbProduct="Emergency Loan" paidBy="Y" customerNumber="430833" totalDue="757" /x>
<x customerName="John" attendance="P" collectedAmount="700" isOverdrafted="0" loanDisbProduct="#NULL" paidBy="Y" customerNumber="192222" totalDue="788" /x>
<x customerName="weldon" attendance="P" collectedAmount="771" isOverdrafted="0" loanDisbProduct="Emergency Loan" paidBy="Y" customerNumber="435874" totalDue="757" /x>
The idea in short:
We replace the non-quoted values (false, true, null) with a quoted place holder
We use various replacements to get the attribute centered XML
Use this query to get the values
SELECT cd.id
,OneCustomer.value('#customerName','nvarchar(max)') AS CustomerName
,OneCustomer.value('#attendance','nvarchar(max)') AS Attendance
--more attributes
FROM #customerData cd
CROSS APPLY(SELECT REPLACE(REPLACE(REPLACE(cd.rawData,'false','"0"'),'true','"1"'),'null','"#NULL"')) A(JustStringValues)
CROSS APPLY(SELECT CAST(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(JustStringValues,'[',''),']',''),'},{"',' /><x '),'{"','<x '),'}',' />'),'","','" '),'":"','="') AS XML)) B(SinlgeRow)
CROSS APPLY B.SinlgeRow.nodes('/x') AS C(OneCustomer);

Order by for column in varchar type

I have the following column strand which is ordered in ascending order but its taking 3.10 as next after 3.1 instead of 3.2..
the column is varchar type..
Strand
3.1
3.1.1
3.1.1.1
3.1.1.2
3.1.2
3.1.2.1
3.10 # wrong
3.10.1 # wrong
3.10.1.1 # wrong
3.2 <- this should have been after 3.1.2.1
3.2.1
3.2.1.1
..
3.9
3.9.1.1
<- here is where 3.10 , 3.10.1 and 3.10.1.1 should reside
I used the following query to order it;
SELECT * FROM [table1]
ORDER BY RPAD(Strand,4,'.0') ;
how to make sure its ordered in the right way such that 3.10,3.10.1 and 3.10.1.1 is at last
Try this:
DROP TABLE T1;
CREATE TABLE T1 (Strand VARCHAR(20));
INSERT INTO T1 VALUES ('3.1');
INSERT INTO T1 VALUES('3.1.1');
INSERT INTO T1 VALUES('3.1.1.1');
INSERT INTO T1 VALUES('3.1.1.2');
INSERT INTO T1 VALUES('3.2');
INSERT INTO T1 VALUES('3.2.1');
INSERT INTO T1 VALUES('3.10');
INSERT INTO T1 VALUES('3.10.1');
SELECT * FROM T1
ORDER BY STRAND;
SELECT *
FROM T1
ORDER BY
CAST(SUBSTRING_INDEX(CONCAT(Strand+'.0.0.0.0','.',1) AS UNSIGNED INTEGER) *1000 +
CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(CONCAT(Strand,'.0.0.0.0'),'.',2),'.',-1) AS UNSIGNED INTEGER) *100 +
CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(CONCAT(Strand,'.0.0.0.0'),'.',3),'.',-1) AS UNSIGNED INTEGER) *10 +
CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(CONCAT(Strand,'.0.0.0.0'),'.',4),'.',-1) AS UNSIGNED INTEGER)
Output not ordeded:
Strand
1 3.1
2 3.1.1
3 3.1.1.1
4 3.1.1.2
5 3.10
6 3.10.1
7 3.2
8 3.2.1
Output Ordered:
Strand
1 3.1
2 3.1.1
3 3.1.1.1
4 3.1.1.2
5 3.2
6 3.2.1
7 3.10
8 3.10.1
you can order the result baset on the integer value of your field. your code will looks like
select [myfield]from [mytable] order by
convert(RPAD(replace([myfield],'.',''),4,0),UNSIGNED INTEGER);
in this code replace function will cleand the dots (.)
hope thin help
You must normalize each group of digits
SELECT * FROM [table1]
ORDER BY CONCAT(
LPAD(SUBSTRING_INDEX(Strand,'.',1),3,'0'), '-',
LPAD(SUBSTRING_INDEX(SUBSTRING_INDEX(Strand,'.',2),'.',-1),3,'0'), '-',
LPAD(SUBSTRING_INDEX(SUBSTRING_INDEX(Strand,'.',3),'.',-1),3,'0'), '-',
LPAD(SUBSTRING_INDEX(SUBSTRING_INDEX(Strand,'.',3),'.',-1),3,'0'));
sample
mysql> SELECT CONCAT(
-> LPAD(SUBSTRING_INDEX('3.10.1.1','.',1),3,'0'), '-',
-> LPAD(SUBSTRING_INDEX(SUBSTRING_INDEX('3.10.1.1','.',2),'.',-1),3,'0'), '-',
-> LPAD(SUBSTRING_INDEX(SUBSTRING_INDEX('3.10.1.1','.',3),'.',-1),3,'0'), '-',
-> LPAD(SUBSTRING_INDEX(SUBSTRING_INDEX('3.10.1.1','.',3),'.',-1),3,'0'));
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| CONCAT(
LPAD(SUBSTRING_INDEX('3.10.1.1','.',1),3,'0'), '-',
LPAD(SUBSTRING_INDEX(SUBSTRING_INDEX('3.10.1.1','.',2),'.',-1),3,'0'), '-',
LPAD(SUBSTRING_INDEX(SUBSTRING_INDEX('3.10.1.1','.',3),'.',-1),3,'0'), '-',
LPAD(SUBSTRING_INDEX(SUBSTRI |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| 003-010-001-001 |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0,00 sec)
Cause "strand" column is text data, so it will be ordered in alphabetical. To make it be ordered as your desire, you should format your data before insert or update it. Suppose maximum digit for each level is 3, your data should be formated like this
003.001
003.001.001
003.001.001.001
003.002
003.002.001
003.002.001.001
003.010
010.001
The altenative way is splitting "strand" column into mutiple columns. Each column will store data for each level, such as
Level1 | Level2 | Level3 ...
3 | 1 | 0
3 | 1 | 1
3 | 2 | 0
...
3 | 10 | 0
Datatype of these columns should be number and then you should be able to order by these columns.
If the point(.) in your data is no more than 3, you can try this:
select *
from demo
order by replace(Strand, '.', '') * pow(10, (3 + length(replace(Strand, '.', '')) - length(Strand)))
If the point is uncertain, here you can should use subquery to get max num of point:
select demo.Strand
from demo
cross join (
select max(length(Strand) - length(replace(Strand, '.', ''))) as num from demo
) t
order by replace(Strand, '.', '') * pow(10, (num + length(replace(Strand, '.', '')) - length(Strand)))
See demo in Rextester.
As you see, I've used function replace, length, pow in order by clause.
1) replace(Strand, '.', '') will give us int number, like:
replace('3.10.1.1', '.', '') => 31011;
2) (3 + length(replace(Strand, '.', '')) - length(Strand)) will give us the count of point which the max num of point minus point's count in Strand, like:
3.1 => 2;
3)pow returns the value of X raised to the power of Y;
so the sample data will be calculated like:
3100
3110
3111
3112
3120
3121
31000
31010
31011
3200
3210
3211
3900
3911
by these nums, you will get the right sort.

Parse text using substring in mysql

I want to parse a text using substring. The format we have for the text is like this:
N, Adele, A, 18
And the substring we do is like this:
SUBSTRING_INDEX(SUBSTRING_INDEX(text, ',', 2), ', ', -1) as 'Name',
SUBSTRING_INDEX(SUBSTRING_INDEX(text, ',', 4), ', ', -1) as 'Age',
The output we get is:
| Name | Age |
| Adele | 18 |
But we want to change the text format to:
N Adele, A 18
What would be the correct syntax so can I parse the text in the position 1 (N Adele) and use the delimiter space and just get Adele? And then same for the next text (A 18)?
I tried doing
SUBSTRING_INDEX(SUBSTRING_INDEX(text, ' ', 1), ', ', -1) as 'Name',
But the output I got is just
| Name |
| N |
The output I was hoping for is like this:
| Name |
| Adele |
Presuming here that you want to change your original data structure and still be able to get the results out. You change your data structure to:
N Adele, A 18 -- etc
With the potential to have multiple names as the name (space separated), my previous example is not correct.
You could trim off the N and A directly with their space, knowing that they will only ever be two characters long and that they will always be there, like this:
SUBSTRING(TRIM(SUBSTRING_INDEX(`text`, ',', 1)), 3) AS 'Name',
SUBSTRING(TRIM(SUBSTRING_INDEX(`text`, ',', -1)), 3) AS 'Age'
To get:
Name | Age
--------------------
Adele | 18
You can use
SELECT
SUBSTRING(text, 2, INSTR(text, ',') - INSTR(text, ' ')) AS Name,
SUBSTRING(text, INSTR(text, ',') + 3, LENGTH(text) - INSTR(text, ',') + 3) AS Age
FROM your_table;
as the position of the field descriptors (N and A) are fixed (relative to the start of the string and to the comma). You can check the working query in this fiddle.

split characters and numbers in MySQL

I have a column in my table like this,
students
--------
abc23
def1
xyz567
......
and so on. Now i need output like only names
Need output as
students
--------
abc
def
xyz
How can i get this in mysql. Thanks advance.
You can do it with string functions ans some CAST() magic:
SELECT
SUBSTR(
name,
1,
CHAR_LENGTH(#name) - CHAR_LENGTH(
IF(
#c:=CAST(REVERSE(name) AS UNSIGNED),
#c,
''
)
)
)
FROM
students
for example:
SET #name:='abc12345';
mysql> SELECT SUBSTR(#name, 1, CHAR_LENGTH(#name) - CHAR_LENGTH(IF(#c:=CAST(REVERSE(#name) AS UNSIGNED), #c, ''))) AS name;
+------+
| name |
+------+
| abc |
+------+

PostgreSQL function with a loop

I'm not good at postgres functions. Could you help me out?
Say, I have this db:
name | round |position | val
-----------------------------------
A | 1 | 1 | 0.5
A | 1 | 2 | 3.4
A | 1 | 3 | 2.2
A | 1 | 4 | 3.8
A | 2 | 1 | 0.5
A | 2 | 2 | 32.3
A | 2 | 3 | 2.21
A | 2 | 4 | 0.8
I want to write a Postgres function that can loop from position=1 to position=4 and calculate the corresponding value. I could do this in python with psycopg2:
import psycopg2
import psycopg2.extras
conn = psycopg2.connect("host='localhost' dbname='mydb' user='user' password='pass'")
CURSOR = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cmd = """SELECT name, round, position, val from mytable"""
CURSOR.execute(cmd)
rows = CURSOR.fetchall()
dict = {}
for row in rows:
indx = row['round']
try:
dict[indx] *= (1-row['val']/100)
except:
dict[indx] = (1-row['val']/100)
if row['position'] == 4:
if indx == 1:
result1 = dict[indx]
elif indx == 2:
result2 = dict[indx]
print result1, result2
How can I do the same thing directly in Postgres so that it returns a table of (name, result1, result2)
UPDATE:
#a_horse_with_no_name, the expected value would be:
result1 = (1 - 0.5/100) * (1 - 3.4/100) * (1 - 2.2/100) * (1 - 3.8/100) = 0.9043
result2 = (1 - 0.5/100) * (1 - 32.3/100) * (1 - 2.21/100) * (1 - 0.8/100) = 0.6535
#Glenn gave you a very elegant solution with an aggregate function. But to answer your question, a plpgsql function could look like this:
Test setup:
CREATE TEMP TABLE mytable (
name text
, round int
, position int
, val double precision
);
INSERT INTO mytable VALUES
('A', 1, 1, 0.5)
, ('A', 1, 2, 3.4)
, ('A', 1, 3, 2.2)
, ('A', 1, 4, 3.8)
, ('A', 2, 1, 0.5)
, ('A', 2, 2, 32.3)
, ('A', 2, 3, 2.21)
, ('A', 2, 4, 0.8)
;
Generic function
CREATE OR REPLACE FUNCTION f_grp_prod()
RETURNS TABLE (name text
, round int
, result double precision)
LANGUAGE plpgsql STABLE AS
$func$
DECLARE
r mytable%ROWTYPE;
BEGIN
-- init vars
name := 'A'; -- we happen to know initial value
round := 1; -- we happen to know initial value
result := 1;
FOR r IN
SELECT *
FROM mytable m
ORDER BY m.name, m.round
LOOP
IF (r.name, r.round) <> (name, round) THEN -- return result before round
RETURN NEXT;
name := r.name;
round := r.round;
result := 1;
END IF;
result := result * (1 - r.val/100);
END LOOP;
RETURN NEXT; -- return final result
END
$func$;
Call:
SELECT * FROM f_grp_prod();
Result:
name | round | result
-----+-------+---------------
A | 1 | 0.90430333812
A | 2 | 0.653458283632
Specific function as per question
CREATE OR REPLACE FUNCTION f_grp_prod(text)
RETURNS TABLE (name text
, result1 double precision
, result2 double precision)
LANGUAGE plpgsql STABLE AS
$func$
DECLARE
r mytable%ROWTYPE;
_round integer;
BEGIN
-- init vars
name := $1;
result2 := 1; -- abuse result2 as temp var for convenience
FOR r IN
SELECT *
FROM mytable m
WHERE m.name = name
ORDER BY m.round
LOOP
IF r.round <> _round THEN -- save result1 before 2nd round
result1 := result2;
result2 := 1;
END IF;
result2 := result2 * (1 - r.val/100);
_round := r.round;
END LOOP;
RETURN NEXT;
END
$func$;
Call:
SELECT * FROM f_grp_prod('A');
Result:
name | result1 | result2
-----+---------------+---------------
A | 0.90430333812 | 0.653458283632
I guess you are looking for an aggregate "product" function. You can create your own aggregate functions in Postgresql and Oracle.
CREATE TABLE mytable(name varchar(32), round int, position int, val decimal);
INSERT INTO mytable VALUES('A', 1, 1, 0.5);
INSERT INTO mytable VALUES('A', 1, 2, 3.4);
INSERT INTO mytable VALUES('A', 1, 3, 2.2);
INSERT INTO mytable VALUES('A', 1, 4, 3.8);
INSERT INTO mytable VALUES('A', 2, 1, 0.5);
INSERT INTO mytable VALUES('A', 2, 2, 32.3);
INSERT INTO mytable VALUES('A', 2, 3, 2.21);
INSERT INTO mytable VALUES('A', 2, 4, 0.8);
CREATE AGGREGATE product(double precision) (SFUNC=float8mul, STYPE=double precision, INITCOND=1);
SELECT name, round, product(1-val/100) AS result
FROM mytable
GROUP BY name, round;
name | round | result
------+-------+----------------
A | 2 | 0.653458283632
A | 1 | 0.90430333812
(2 rows)
See "User-Defined Aggregates" in the Postgresql doc. The example above I borrowed from
here. There are other stackoverflow responses that show other methods to do this.