How to convert multiple values in the row with comma separator into multiple columns? - sql

How to convert multiple comma separated values in rows into multiple columns in SQL Server like I have a table with two rows
A1,1,B1,2
C1,3,D4,4
I want output like this
col1 col2 col3 col4
A1 1 B1 2
C1 3 D4 4

Another option if you have a finite or max number of columns
Example
Declare #YourTable Table ([YourCol] varchar(50))
Insert Into #YourTable Values
('A1,1,B1,2')
,('C1,3,D4,4')
Select B.*
From #YourTable A
Cross Apply (
Select Pos1 = ltrim(rtrim(xDim.value('/x[1]','varchar(max)')))
,Pos2 = ltrim(rtrim(xDim.value('/x[2]','varchar(max)')))
,Pos3 = ltrim(rtrim(xDim.value('/x[3]','varchar(max)')))
,Pos4 = ltrim(rtrim(xDim.value('/x[4]','varchar(max)')))
,Pos5 = ltrim(rtrim(xDim.value('/x[5]','varchar(max)')))
,Pos6 = ltrim(rtrim(xDim.value('/x[6]','varchar(max)')))
From (Select Cast('<x>' + replace((Select replace(A.YourCol,',','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml) as xDim) as x
) B
Returns
Pos1 Pos2 Pos3 Pos4 Pos5 Pos6
A1 1 B1 2 NULL NULL
C1 3 D4 4 NULL NULL
EDIT - Just for Fun, Here is a Dynamic Version of the Above
Just replace YourTable with your actual table name, and YourCol with the desired column to split.
Declare #SQL nvarchar(max)
Set #SQL = Stuff((Select concat(',Col',N,' = ltrim(rtrim(xDim.value(''/x[',N,']'',''varchar(max)'')))')
From (
Select Top ((Select max(len(YourCol)-len(replace(YourCol,',','')))+1 From YourTable))
N=Row_Number() Over (Order By (Select NULL))
From master..spt_values
) A
For XML Path ('')),1,1,'')
Set #SQL = '
Select A.*,B.*
From YourTable A
Cross Apply ( Select ' + #SQL +' From (Select Cast(''<x>'' + replace((Select replace(A.YourCol,'','',''§§Split§§'') as [*] For XML Path('''')),''§§Split§§'',''</x><x>'')+''</x>'' as xml) as xDim ) x ) B
'
--Print #SQL
Exec(#SQL)
Returns
YourCol Col1 Col2 Col3 Col4
A1,1,B1,2 A1 1 B1 2
C1,3,D4,4 C1 3 D4 4

Assuming your table name is t, you can follow the steps below
Step 1: Split the columns using the CSV tally type splitter
Step 2: PIVOT out the values
In a single query the solution will be
select * from
(
select
t.col as col,
row_number() over (partition by t.col order by t1.N asc) as row_num,
SUBSTRING( t.col, t1.N, ISNULL(NULLIF(CHARINDEX(',',t.col,t1.N),0)-t1.N,4000)) as split_values
from t
join
(
select
t.col,
1 as N
from t
UNION ALL
select
t.col,
t1.N + 1 as N
from t
join
(
select
top 4000
row_number() over(order by (select NULL)) as N
from
sys.objects s1
cross join
sys.objects s2
) t1
on SUBSTRING(t.col,t1.N,1) = ','
) t1
on t1.col=t.col
)src
PIVOT
( max(split_values) for row_num in ([1],[2],[3],[4],[5],[6],[7],[8]))p
working demo
PS: You can actually use a dynamic pivot if you do not know the maximum commas in the columns.

Related

SQL Query on sort key values

how can you sort data in sql for each column ??
for example C1 column have value in first row as 'CAB' and you want in output as 'ABC'
Input
C1
CAB
ZSA
Output
C1
ABC
ASZ
You could try this logic, maybe there is a better solution, but it does the job
DECLARE #t TABLE (Id INT, C1 VARCHAR(255))
INSERT INTO #t VALUES (1, 'CAB'),(2, 'ZSA')
;WITH mcte AS (
SELECT split.Id, split.C1, split.c, ASCII(split.c) AS asciinr
FROM (
SELECT a.Id, a.C1, SUBSTRING(a.C1, v.number+1, 1) AS c
FROM #t AS a
join master..spt_values v on v.number < LEN(a.C1)
WHERE v.type = 'P'
) AS split
)
SELECT Id, c1, REPLACE(STUFF((SELECT ' ' + mcte2.c FROM mcte AS mcte2
WHERE mcte2.C1 = mcte.C1 and mcte2.Id = mcte.Id
ORDER BY mcte2.asciinr FOR XML PATH('') ), 1, 1, ''), ' ', '') as OrderedC1
FROM mcte
GROUP BY Id, c1
ORDER BY mcte.C1
Result
Id C1 OrderderC1
-------------------
1 CAB ABC
2 ZSA ASZ

MS SQL Server Get value between commas

I have a column in Table1 with string in it separated by commma:
Id Val
1 ,4
2 ,3,1,0
3 NULL
4 ,5,2
Is there a simple way to split and get any value from that column,
for example
SELECT Value(1) FROM Table1 should get
Id Val
1 4
2 3
3 NULL
4 5
SELECT Value(2) FROM Table1 should get
Id Val
1 NULL
2 1
3 NULL
4 2
Thank you!
Storing comma separated values in a column is always a pain, consider changing your table structure
To get this done, create a split string function. Here is one of the best possible approach to split the string to individual rows. Referred from http://www.sqlservercentral.com/articles/Tally+Table/72993/
CREATE FUNCTION [dbo].[DelimitedSplit8K]
(#pString VARCHAR(8000), #pDelimiter CHAR(1))
RETURNS TABLE WITH SCHEMABINDING AS
RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 0 up to 10,000...
-- enough to cover NVARCHAR(4000)
WITH E1(N) AS (
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), --10E+1 or 10 rows
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
-- for both a performance gain and prevention of accidental "overruns"
SELECT TOP (ISNULL(DATALENGTH(#pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
SELECT 1 UNION ALL
SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(#pString,t.N,1) = #pDelimiter
),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
SELECT s.N1,
ISNULL(NULLIF(CHARINDEX(#pDelimiter,#pString,s.N1),0)-s.N1,8000)
FROM cteStart s
)
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
Item = SUBSTRING(#pString, l.N1, l.L1)
FROM cteLen l
to call the function
SELECT *
FROM yourtable
CROSS apply (SELECT CASE WHEN LEFT(val, 1) = ',' THEN Stuff(val, 1, 1, '') ELSE val END) cs (cleanedval)
CROSS apply [dbo].[Delimitedsplit8k](cs.cleanedval, ',')
WHERE ItemNumber = 1
SELECT *
FROM yourtable
CROSS apply (SELECT CASE WHEN LEFT(val, 1) = ',' THEN Stuff(val, 1, 1, '') ELSE val END) cs (cleanedval)
CROSS apply [dbo].[Delimitedsplit8k](cs.cleanedval, ',')
WHERE ItemNumber = 2
Another option using a Parse/Split Function and an OUTER APPLY
Example
Declare #YourTable Table ([Id] int,[Val] varchar(50))
Insert Into #YourTable Values
(1,',4')
,(2,',3,1,0')
,(3,NULL)
,(4,',5,2')
Select A.ID
,Val = B.RetVal
From #YourTable A
Outer Apply (
Select * From [dbo].[tvf-Str-Parse](A.Val,',')
Where RetSeq = 2
) B
Returns
ID Val
1 4
2 3
3 NULL
4 5
The UDF if Interested
CREATE FUNCTION [dbo].[tvf-Str-Parse] (#String varchar(max),#Delimiter varchar(10))
Returns Table
As
Return (
Select RetSeq = Row_Number() over (Order By (Select null))
,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
From (Select x = Cast('<x>' + replace((Select replace(#String,#Delimiter,'§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A
Cross Apply x.nodes('x') AS B(i)
);
Here is an example of using a CTE combined with converting the CSV to XML:
DECLARE #Test TABLE (
CsvData VARCHAR(10)
);
INSERT INTO #Test (CsvData)
VALUES
('1,2,3'),
(',4,5,7'),
(NULL),
(',3,');
WITH XmlData AS (
SELECT CONVERT(XML, '<val>' + REPLACE(CsvData, ',', '</val><val>') + '</val>') [CsvXml]
FROM #Test
)
SELECT xd.CsvXml.value('val[2]', 'VARCHAR(10)')
FROM XmlData xd;
This would output:
2
4
NULL
3
The column to display is controlled by the XPath query. In this case, val[2].
The main advantage here is that no user-defined functions are required.
Try This Logic Using recursive CTE
DECLARE #Pos INT = 2
DECLARE #T TABLE
(
Id INT,
Val VARCHAR(50)
)
INSERT INTO #T
VALUES(1,',4'),(2,',3,1,0'),(3,NULL),(4,',5,2')
;WITH CTE
AS
(
SELECT
Id,
SeqNo = 0,
MyStr = SUBSTRING(Val,CHARINDEX(',',Val)+1,LEN(Val)),
Num = REPLACE(SUBSTRING(Val,1,CHARINDEX(',',Val)),',','')
FROM #T
UNION ALL
SELECT
Id,
SeqNo = SeqNo+1,
MyStr = CASE WHEN CHARINDEX(',',MyStr)>0
THEN SUBSTRING(MyStr,CHARINDEX(',',MyStr)+1,LEN(MyStr))
ELSE NULL END,
Num = CASE WHEN CHARINDEX(',',MyStr)>0
THEN REPLACE(SUBSTRING(MyStr,1,CHARINDEX(',',MyStr)),',','')
ELSE MyStr END
FROM CTE
WHERE ISNULL(REPLACE(MyStr,',',''),'')<>''
)
SELECT
T.Id,
CTE.Num
FROM #T t
LEFT JOIN CTE
ON T.Id = cte.Id
AND SeqNo = #Pos
My Output for the above
Test Data
Declare #t TABLE (Id INT , Val VARCHAR(100))
INSERT INTO #t VALUES
(1 , '4'),
(2 , '3,1,0'),
(3 , NULL),
(4 , '5,2')
Function Definition
CREATE FUNCTION [dbo].[fn_xml_Splitter]
(
#delimited nvarchar(max)
, #delimiter nvarchar(1)
, #Position INT = NULL
)
RETURNS TABLE
AS
RETURN
(
SELECT Item
FROM (
SELECT Split.a.value('.', 'VARCHAR(100)') Item
, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) ItemNumber
FROM
(SELECT Cast ('<X>' + Replace(#delimited, #delimiter, '</X><X>')
+ '</X>' AS XML) AS Data
) AS t CROSS APPLY Data.nodes ('/X') AS Split(a)
)x
WHERE x.ItemNumber = #Position OR #Position IS NULL
);
GO
Function Call
Now you can call this function in two different ways.
1 . to get return an Item on a specific position, specify the position in the 3rd parameter of the function:
SELECT *
FROM #t t
CROSS APPLY [dbo].[fn_xml_Splitter](t.Val , ',', 1)
2 . to get return all items, specify the key word DEFUALT in the 3rd parameter of the function:
SELECT *
FROM #t t
CROSS APPLY [dbo].[fn_xml_Splitter](t.Val , ',', DEFAULT)

SQL: How to create columns dynamically

I have a table which is created dynamically. So the number of columns is unknown at the time of creation. I want to create copies of each column in the same table with first column holding the first part of comma separated value, second column the second part and so on
For example,
ID Value1 Value2 .... Valuen
1 1;2;3 4;5;6
2 A;B;C D;E;F
I want to get the output like
ID Value1Copy1 Value1Copy2 Value1Copy3 Value2Copy1 Value2Copy2 Value2Copy3 .... ValuenCopy1
1 1 2 3 4 5 6
2 A B C D E F
I am unable to achieve this for variable number of columns
The following will dynamically unpivot your data. You may notice that the only field specified is ID.
The results are dropped into a #Temp table. From there we perform a dynamic pivot
Example
Declare #YourTable table (ID int,Value1 varchar(50),Value2 varchar(50))
Insert Into #YourTable values
( 1, '1;2;3','4;5;6'),
( 2, 'A;B;C','D;E;F')
Select A.ID
,Col = concat(C.Item,'Copy',D.RetSeq)
,Value = D.RetVal
Into #Temp
From #YourTable A --<< Replace with Your actual table
Cross Apply (Select XMLData = cast((Select A.* For XML Raw) as xml ) ) B
Cross Apply (
Select Item = attr.value('local-name(.)','varchar(100)')
,Value = attr.value('.','varchar(max)')
From B.XMLData.nodes('/row') as A(r)
Cross Apply A.r.nodes('./#*') AS B(attr)
Where attr.value('local-name(.)','varchar(100)') not in ('ID','Other2Exclude')
) C
Cross Apply (
Select RetSeq = Row_Number() over (Order By (Select null))
,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
From (Select x = Cast('<x>' + replace((Select replace(C.Value,';','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A
Cross Apply x.nodes('x') AS B(i)
) D
Where A.ID is not null -- or any other WHERE statement
Declare #SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName(Col) From #Temp Order by 1 For XML Path('')),1,1,'')
Select #SQL = '
Select *
From #Temp
Pivot (max(Value) For [Col] in (' + #SQL + ') ) p'
Exec(#SQL);
Returns

Split SQL server string that has Decimal points into multiple Columns

I have the following table
Col
=========================
1270.8/847.2/254.16/106.9
And I would like to be split into columns like so:
Col1 Col2 Col3 Col4
============================================
1270.8 847.2 254.16 106.9
I have the code below, but it doesn't take the decimal into consideration.
Declare #Sample Table
(MachineName varchar(max))
Insert into #Sample
values ('1270.8/847.2/254.16');
SELECT
Reverse(ParseName(Replace(Reverse(MachineName), '/', ''), 1)) As [M1]
, Reverse(ParseName(Replace(Reverse(MachineName), '/', ''), 2)) As [M2]
, Reverse(ParseName(Replace(Reverse(MachineName), '/', ''), 3)) As [M3]
FROM #Sample
In SQL Server 2016+ you can use string_split().
In SQL Server pre-2016, using a CSV Splitter table valued function by Jeff Moden and conditional aggregation:
declare #Sample Table (id int not null identity(1,1), MachineName varchar(max));
insert into #Sample values ('1270.8/847.2/254.16'),('1270.8/847.2/254.16/106.9');
select
t.id
, m1 = max(case when s.ItemNumber = 1 then s.Item end)
, m2 = max(case when s.ItemNumber = 2 then s.Item end)
, m3 = max(case when s.ItemNumber = 3 then s.Item end)
, m4 = max(case when s.ItemNumber = 4 then s.Item end)
from #Sample t
cross apply dbo.delimitedsplit8K(MachineName,'/') s
group by id
rextester demo: http://rextester.com/WJVLB77682
returns:
+----+--------+-------+--------+-------+
| id | m1 | m2 | m3 | m4 |
+----+--------+-------+--------+-------+
| 1 | 1270.8 | 847.2 | 254.16 | NULL |
| 2 | 1270.8 | 847.2 | 254.16 | 106.9 |
+----+--------+-------+--------+-------+
splitting strings reference:
Tally OH! An Improved SQL 8K “CSV Splitter” Function - Jeff Moden
Splitting Strings : A Follow-Up - Aaron Bertrand
Split strings the right way – or the next best way - Aaron Bertrand
string_split() in SQL Server 2016 : Follow-Up #1 - Aaron Bertrand
Everyone should have a good split/parse function as illustrated by SQLZim (+1), but another option could be as follow:
Declare #YourTable table (ID int,Col varchar(max))
Insert Into #YourTable values
(1,'1270.8/847.2/254.16/106.9')
Select A.ID
,B.*
From #YourTable A
Cross Apply (
Select Col1 = xDim.value('/x[1]','float')
,Col2 = xDim.value('/x[2]','float')
,Col3 = xDim.value('/x[3]','float')
,Col4 = xDim.value('/x[4]','float')
From (Select Cast('<x>' + replace((Select replace(A.Col,'/','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml) as xDim) as A
) B
Returns
ID Col1 Col2 Col3 Col4
1 1270.8 847.2 254.16 106.9
EDIT - If 2012+, and just to be super-duper safe
Select A.ID
,B.*
From #YourTable A
Cross Apply (
Select Col1 = try_convert(float,xDim.value('/x[1]','varchar(100)'))
,Col2 = try_convert(float,xDim.value('/x[2]','varchar(100)'))
,Col3 = try_convert(float,xDim.value('/x[3]','varchar(100)'))
,Col4 = try_convert(float,xDim.value('/x[4]','varchar(100)'))
From (Select Cast('<x>' + replace((Select replace(A.Col,'/','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml) as xDim) as A
) B
If you are using SQL Server 2016, you can use String_Split()
;with cte as (
select RowN = row_number() over(order by (SELECT NULL)), * from string_split('1270.8/847.2/254.16/106.9','/')
) select * from cte
pivot (max(value) for RowN in ([1],[2],[3],[4])) p
If you are using less than SQL Server 2016 version then you might require to use custom split functions... Many ways to write custom split function one easier way is to write using xml
CREATE Function dbo.udf_split( #str varchar(max), #delimiter as varchar(5) )
RETURNS #retTable Table
( RowN int,
value varchar(max)
)
AS
BEGIN
DECLARE #xml as xml
SET #xml = cast(('<X>'+replace(#str,#delimiter ,'</X><X>')+'</X>') as xml)
INSERT INTO #retTable
SELECT RowN = Row_Number() over (order by (SELECT NULL)), N.value('.', 'varchar(MAX)') as value FROM #xml.nodes('X') as T(N)
RETURN
END
--Your query
;with cte as (
select * from udf_split('1270.8/847.2/254.16/106.9','/')
) select * from cte
pivot (max(value) for RowN in ([1],[2],[3],[4])) p
But mine is similar to John's solution... Just now only looking at that
If you are using in value in a table then you can use cross apply as below
create table #t (v varchar(50), i int)
insert into #t (v, i) values ('1270.8/847.2/254.16/106.9',1)
,('847.222/254.33/106.44',2)
select * from #t t cross apply string_split(t.v, '/')
create table #t (v varchar(50), i int)
insert into #t (v, i) values ('1270.8/847.2/254.16/106.9',1)
,('847.222/254.33/106.44',2)
--Just to get all the values
select * from #t t cross apply string_split(t.v, '/')
--Inorder to get into same row -pivoting the data
select * from (
select * from #t t cross apply (select RowN=Row_Number() over (Order by (SELECT NULL)), value from string_split(t.v, '/') ) d) src
pivot (max(value) for src.RowN in([1],[2],[3],[4])) p

SQL Server- PIVOT table. transform row into columns

I am trying to convert rows into columns. here is my query
SELECT M.urn,
M.eventdate,
M.eventlocation,
M.eventroom,
M.eventbed,
N.time
FROM admpatevents M
INNER JOIN admpattransferindex N
ON M.urn = N.urn
AND M.eventseqno = N.eventseqno
AND M.eventdate = N.eventdate
WHERE M.urn = 'F1002754364'
AND M.eventcode = 'TFRADMIN'
Current result
URN Date Location Room Bed Time
F1002754364 20121101 EDEXPRESS 4-152 02 0724
F1002754364 20121101 CARDSURG 3-110 02 1455
F1002754364 20121102 CHEST UNIT 6-129-GL04 1757
required result
F1002754364 20121101 EDEXPRESS 4-152 02 0724 20121101 CARDSURG 3-110 02 1455 20121102 CHEST UNIT 6-129-GL 04 1757
Thanks for your help.
Since you are using SQL Server you can use both the UNPIVOT and PIVOT functions to transform this data. If you know how many values to you will have then you can hard-code the values similar to this:
select *
from
(
select urn,
value,
col +'_'+ CAST(rn as varchar(10)) as col
from
(
SELECT M.urn,
cast(M.eventdate as varchar(50)) eventdate,
M.eventlocation,
M.eventroom,
M.eventbed,
cast(N.time as varchar(50)) time,
ROW_NUMBER() over(PARTITION by m.urn order by m.eventdate) rn
FROM admpatevents M
INNER JOIN admpattransferindex N
ON M.urn = N.urn
AND M.eventseqno = N.eventseqno
AND M.eventdate = N.eventdate
WHERE M.urn = 'F1002754364'
AND M.eventcode = 'TFRADMIN'
) src1
unpivot
(
value
for col in (eventdate, eventlocation, eventroom, eventbed, time)
) unpiv
) src2
pivot
(
max(value)
for col in ([eventdate_1], [eventlocation_1], [eventroom_1], [eventbed_1], [time_1],
[eventdate_2], [eventlocation_2], [eventroom_2], [eventbed_2], [time_2],
[eventdate_3], [eventlocation_3], [eventroom_3], [eventbed_3], [time_3])
) piv
Note- not tested
If you have an unknown number of columns, then you can use dynamic sql similar to this:
DECLARE #query AS NVARCHAR(MAX),
#colsPivot as NVARCHAR(MAX)
select #colsPivot = STUFF((SELECT ','
+ quotename(c.name +'_'+ cast(t.rn as varchar(10)))
from
(
select ROW_NUMBER() over(PARTITION by m.urn order by m.eventdate) rn
FROM admpatevents M
INNER JOIN admpattransferindex N
ON M.urn = N.urn
AND M.eventseqno = N.eventseqno
AND M.eventdate = N.eventdate
WHERE M.urn = 'F1002754364'
) t
cross apply sys.columns as C
where C.object_id IN (object_id('admpatevents'), object_id('admpattransferindex')) and
C.name not in ('urn') -- add any other columns your want to exclude
group by c.name, t.rn
order by t.rn
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query
= 'select *
from
(
select urn, value, col +''_''+ CAST(rn as varchar(10)) as col
from
(
SELECT M.urn,
cast(M.eventdate as varchar(20)) eventdate,
M.eventlocation,
M.eventroom,
M.eventbed,
cast(N.time as varchar(20)) time,
ROW_NUMBER() over(PARTITION by m.urn order by m.eventdate) rn
FROM admpatevents M
INNER JOIN admpattransferindex N
ON M.urn = N.urn
AND M.eventseqno = N.EVENTseqno
AND M.eventdate = N.eventdate
WHERE M.urn = ''F1002754364''
) x
unpivot
(
value
for col in (eventdate, eventlocation, eventroom, eventbed, time)
) u
) x1
pivot
(
max(value)
for col in ('+ #colspivot +')
) p'
exec(#query)
See SQL Fiddle with Demo