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);
Related
I have two columns to compare in a MYSQL table and wanted to split the value of first column to an array and look for any of these values in arrays matches with the values in array of second columns. Here is an example:
Column1 Column2
Walmart Supercenter Walmart Sams
Home Home Depot
3M Logistics Co. 3M
if my approach is something like this then it will never match
column2 like concat('%',column1,'%')
What I am looking for:
column2 like concat('%',column1[0],'%') or column2 like concat('%',column1[1],'%')
Logic
use custom split_str funciton get column1[0] and column1[1]
.. like .. or .. use REGEXP + |
Schema (MySQL v5.6)
CREATE TABLE T
(`Column1` varchar(19), `Column2` varchar(12))
;
INSERT INTO T
(`Column1`, `Column2`)
VALUES
('Walmart Supercenter', 'Walmart Sams'),
('Home', 'Home Depot'),
('3M Logistics Co.', '3M')
;
CREATE FUNCTION SPLIT_STR(
x VARCHAR(255),
delim VARCHAR(12),
pos INT
)
RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
delim, '');
Query
select *
from T
where `Column2` REGEXP
case when SPLIT_STR(`Column1`, ' ', 2) = '' then
SPLIT_STR(`Column1`, ' ', 1)
else
concat(
SPLIT_STR(`Column1`, ' ', 1)
,'|'
,SPLIT_STR(`Column1`, ' ', 2)
)
end;
| Column1 | Column2 |
| ------------------- | ------------ |
| Walmart Supercenter | Walmart Sams |
| Home | Home Depot |
| 3M Logistics Co. | 3M |
View on DB Fiddle
Although this way can be achieved, but the efficiency is not good
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 |
+------+
I have this table synonym_temp:
id | synonyms
----------------------------
1 | ebay,online,dragon
2 | auto, med
And I want to transfer it to synonym table but each synonym should be inserted separately. Like:
id | synonym
----------------------------
1 | ebay
1 | online
1 | dragon
2 | auto
2 | med
How should I do that? Thanks in advance.
Use PHP
$records=mysql_query("select * from synonm_temp");
foreach($records as $row)
{
$synonums=$row['synonyms'];
$synonums_array=explode(',', $synonums);
$id=$row['id'];
foreach($synonums_array as $syn)
{
mysql_query("insert into synonm_temp values ($id,'$syn') ");
}
}
You can do this with a Numbers or Tally table which contains a sequential list of integers:
Select T.id, Substring(T.synonym, N.Value, Locate(', ', T.synonym+ ', ', N.Value) - N.Value)
From Numbers As N
Cross Join MyTable As T
Where N.Value <= Len(T.synonym)
And Substring(', ' + T.synonym, N.Value, 1) = ', '
In the above case, my Numbers table is structured like so:
Create Table Numbers( Value int not null primary key )
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.
I see that within MySQL there are Cast() and Convert() functions to create integers from values, but is there any way to check to see if a value is an integer? Something like is_int() in PHP is what I am looking for.
I'll assume you want to check a string value. One nice way is the REGEXP operator, matching the string to a regular expression. Simply do
select field from table where field REGEXP '^-?[0-9]+$';
this is reasonably fast. If your field is numeric, just test for
ceil(field) = field
instead.
Match it against a regular expression.
c.f. http://forums.mysql.com/read.php?60,1907,38488#msg-38488 as quoted below:
Re: IsNumeric() clause in MySQL??
Posted by: kevinclark ()
Date: August 08, 2005 01:01PM
I agree. Here is a function I created for MySQL 5:
CREATE FUNCTION IsNumeric (sIn varchar(1024)) RETURNS tinyint
RETURN sIn REGEXP '^(-|\\+){0,1}([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+|[0-9]+)$';
This allows for an optional plus/minus sign at the beginning, one optional decimal point, and the rest numeric digits.
Suppose we have column with alphanumeric field having entries like
a41q
1458
xwe8
1475
asde
9582
.
.
.
.
.
qe84
and you want highest numeric value from this db column (in this case it is 9582) then this query will help you
SELECT Max(column_name) from table_name where column_name REGEXP '^[0-9]+$'
Here is the simple solution for it
assuming the data type is varchar
select * from calender where year > 0
It will return true if the year is numeric else false
This also works:
CAST( coulmn_value AS UNSIGNED ) // will return 0 if not numeric string.
for example
SELECT CAST('a123' AS UNSIGNED) // returns 0
SELECT CAST('123' AS UNSIGNED) // returns 123 i.e. > 0
To check if a value is Int in Mysql, we can use the following query.
This query will give the rows with Int values
SELECT col1 FROM table WHERE concat('',col * 1) = col;
The best i could think of a variable is a int Is a combination with MySQL's functions CAST() and LENGTH().
This method will work on strings, integers, doubles/floats datatypes.
SELECT (LENGTH(CAST(<data> AS UNSIGNED))) = (LENGTH(<data>)) AS is_int
see demo http://sqlfiddle.com/#!9/ff40cd/44
it will fail if the column has a single character value. if column has
a value 'A' then Cast('A' as UNSIGNED) will evaluate to 0 and
LENGTH(0) will be 1. so LENGTH(Cast('A' as UNSIGNED))=LENGTH(0) will
evaluate to 1=1 => 1
True Waqas Malik totally fogotten to test that case. the patch is.
SELECT <data>, (LENGTH(CAST(<data> AS UNSIGNED))) = CASE WHEN CAST(<data> AS UNSIGNED) = 0 THEN CAST(<data> AS UNSIGNED) ELSE (LENGTH(<data>)) END AS is_int;
Results
**Query #1**
SELECT 1, (LENGTH(CAST(1 AS UNSIGNED))) = CASE WHEN CAST(1 AS UNSIGNED) = 0 THEN CAST(1 AS UNSIGNED) ELSE (LENGTH(1)) END AS is_int;
| 1 | is_int |
| --- | ------ |
| 1 | 1 |
---
**Query #2**
SELECT 1.1, (LENGTH(CAST(1 AS UNSIGNED))) = CASE WHEN CAST(1.1 AS UNSIGNED) = 0 THEN CAST(1.1 AS UNSIGNED) ELSE (LENGTH(1.1)) END AS is_int;
| 1.1 | is_int |
| --- | ------ |
| 1.1 | 0 |
---
**Query #3**
SELECT "1", (LENGTH(CAST("1" AS UNSIGNED))) = CASE WHEN CAST("1" AS UNSIGNED) = 0 THEN CAST("1" AS UNSIGNED) ELSE (LENGTH("1")) END AS is_int;
| 1 | is_int |
| --- | ------ |
| 1 | 1 |
---
**Query #4**
SELECT "1.1", (LENGTH(CAST("1.1" AS UNSIGNED))) = CASE WHEN CAST("1.1" AS UNSIGNED) = 0 THEN CAST("1.1" AS UNSIGNED) ELSE (LENGTH("1.1")) END AS is_int;
| 1.1 | is_int |
| --- | ------ |
| 1.1 | 0 |
---
**Query #5**
SELECT "1a", (LENGTH(CAST("1.1" AS UNSIGNED))) = CASE WHEN CAST("1a" AS UNSIGNED) = 0 THEN CAST("1a" AS UNSIGNED) ELSE (LENGTH("1a")) END AS is_int;
| 1a | is_int |
| --- | ------ |
| 1a | 0 |
---
**Query #6**
SELECT "1.1a", (LENGTH(CAST("1.1a" AS UNSIGNED))) = CASE WHEN CAST("1.1a" AS UNSIGNED) = 0 THEN CAST("1.1a" AS UNSIGNED) ELSE (LENGTH("1.1a")) END AS is_int;
| 1.1a | is_int |
| ---- | ------ |
| 1.1a | 0 |
---
**Query #7**
SELECT "a1", (LENGTH(CAST("1.1a" AS UNSIGNED))) = CASE WHEN CAST("a1" AS UNSIGNED) = 0 THEN CAST("a1" AS UNSIGNED) ELSE (LENGTH("a1")) END AS is_int;
| a1 | is_int |
| --- | ------ |
| a1 | 0 |
---
**Query #8**
SELECT "a1.1", (LENGTH(CAST("a1.1" AS UNSIGNED))) = CASE WHEN CAST("a1.1" AS UNSIGNED) = 0 THEN CAST("a1.1" AS UNSIGNED) ELSE (LENGTH("a1.1")) END AS is_int;
| a1.1 | is_int |
| ---- | ------ |
| a1.1 | 0 |
---
**Query #9**
SELECT "a", (LENGTH(CAST("a" AS UNSIGNED))) = CASE WHEN CAST("a" AS UNSIGNED) = 0 THEN CAST("a" AS UNSIGNED) ELSE (LENGTH("a")) END AS is_int;
| a | is_int |
| --- | ------ |
| a | 0 |
see demo
What about:
WHERE table.field = "0" or CAST(table.field as SIGNED) != 0
to test for numeric and the corrolary:
WHERE table.field != "0" and CAST(table.field as SIGNED) = 0
I have tried using the regular expressions listed above, but they do not work for the following:
SELECT '12 INCHES' REGEXP '^(-|\\+){0,1}([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+|[0-9]+)$' FROM ...
The above will return 1 (TRUE), meaning the test of the string '12 INCHES' against the regular expression above, returns TRUE. It looks like a number based on the regular expression used above. In this case, because the 12 is at the beginning of the string, the regular expression interprets it as a number.
The following will return the right value (i.e. 0) because the string starts with characters instead of digits
SELECT 'TOP 10' REGEXP '^(-|\\+){0,1}([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+|[0-9]+)$' FROM ...
The above will return 0 (FALSE) because the beginning of the string is text and not numeric.
However, if you are dealing with strings that have a mix of numbers and letters that begin with a number, you will not get the results you want. REGEXP will interpret the string as a valid number when in fact it is not.
This works well for VARCHAR where it begins with a number or not..
WHERE concat('',fieldname * 1) != fieldname
may have restrictions when you get to the larger NNNNE+- numbers
for me the only thing that works is:
CREATE FUNCTION IsNumeric (SIN VARCHAR(1024)) RETURNS TINYINT
RETURN SIN REGEXP '^(-|\\+){0,1}([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+|[0-9]+)$';
from kevinclark all other return useless stuff for me in case of 234jk456 or 12 inches