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 | 05;06 | 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|05|S|
And so on.
My initial thought is to use a CTE, which I've set up as:
WITH TEST AS(
SELECT DISTINCT Column_A, Column_B, Column_C, VALUE AS Column_D
from [TABLE]
CROSS APPLY STRING_SPLIT(Column_D, ';'))
SELECT \* FROM TEST
;
Though that doesn't seem to produce the correct results, especially after stacking the CTEs and string splits.
As an update, there were really helpful solutions below. They all ran as expected, however I had one last addition. Is it possible/reasonable to ignore a row/column if it's blank? For example, skipping over Column_C where Column_A is '001'. |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|