Programming :  Student Freelance Forum For Work Experience Builders' (CertificationPoint) The fastest message board... ever.
 
'Unpivoting' a SQL table - Updated
Posted by: adcertpoint (Moderator)
Date: July 22, 2021 06:56PM

I'm looking to 'unpivot' a table, though I'm not sure what the best way of going about it, is. Additionally, the values are separated by a ';'. I've listed a sample of what I'm looking at:


Column_A Column_B Column_C Column_D
000 A;B;C;D 01;02;03;04 X;Y;D;E
001 A;B S;T
002 C 07 S

​ From that, I'm looking for a way to unpivot it, but also to keep the relations it's currently in. As in, the first value in Column_B, C, and D are tied together: ​
Column_A Column_B Column_C Column_D
000 A 01 X
000 B 02 Y
000 C 03 D
000 D 04 E
001 A S
001 B T

And so on. I had received some really helpful suggestions earlier, but am having a difficult time handling a use case where a collumn/row cell might be empty of values. The below code snippet is something I had been provided, which utilizes the pre-existing DelimitedSplit8K_LEAD function.

Any help would be really appreciated!

CREATE TABLE dbo.YourTable (ColA varchar(3),
ColB varchar(8000),
ColC varchar(8000),
ColD varchar(8000));
INSERT INTO dbo.YourTable
VALUES('000','A;B;C;D','01;02;03;04','X;Y;D;E'),
('001','A;B','05;06','S;T'),
('002','C','07','S');
GO

SELECT YT.ColA,
DSLB.Item AS ColB,
DSLC.Item AS ColC,
DSLD.Item AS ColD
FROM dbo.YourTable YT
CROSS APPLY dbo.DelimitedSplit8K_LEAD(YT.ColB,';') DSLB
CROSS APPLY dbo.DelimitedSplit8K_LEAD(YT.ColC,';') DSLC
CROSS APPLY dbo.DelimitedSplit8K_LEAD(YT.ColD,';') DSLD
WHERE DSLB.ItemNumber = DSLC.ItemNumber
AND DSLC.ItemNumber = DSLD.ItemNumber;
GO
DROP TABLE dbo.YourTable;

Options: ReplyQuote


Sorry, only registered users may post in this forum.
This forum powered by Phorum.