
Question:
I'd like to stack two columns of a table into a single column. So for example, if the source table is:
| Id | Code_1 | Code_2 | Other |
|----|---------|---------|-------|
| 1 | Value_1 | Value_2 | Row_1 |
| 2 | Value_3 | (null) | Row_2 |
| 3 | (null) | Value_4 | Row_3 |
| 4 | (null) | (null) | Row_4 |
| 5 | Value_5 | (null) | Row_5 |
Then the target table should be:
| Id | Code | Other |
|----|---------|-------|
| 1 | Value_1 | Row_1 |
| 2 | Value_2 | Row_1 |
| 3 | Value_3 | Row_2 |
| 4 | Value_4 | Row_3 |
| 5 | Value_5 | Row_5 |
Notice that the Other
column just duplicates its values, but only when there's a non-null value in Code_1
and Code_2
.
I tried to use a PIVOT statement cos I'm essentially trying to (almost) stack transposes of each row, but I can't figure out how to orchestrate it properly.
I have the DDL is below:
CREATE TABLE Source (
Id INT IDENTITY(1, 1) PRIMARY KEY,
Code_1 VARCHAR(10),
Code_2 VARCHAR(10),
Other VARCHAR(10)
);
INSERT INTO Source VALUES ('Value_1', 'Value_2', 'Row_1'), ('Value_3', NULL, 'Row_2'), (NULL, 'Value_4', 'Row_3'), (NULL, NULL, 'Row_4'), ('Value_5', NULL, 'Row_5');
CREATE TABLE Target (
Id INT IDENTITY(1, 1) PRIMARY KEY,
Code VARCHAR(10),
Other VARCHAR(10)
);
INSERT INTO Target VALUES ('Value_1', 'Row_1'), ('Value_2', 'Row_1'), ('Value_3', 'Row_2'), ('Value_4', 'Row_3'), ('Value_5', 'Row_5')
You need unpivot
:
SELECT Id, Code, Other
FROM
Source
UNPIVOT
(Code FOR code_ IN
(code_1, code_2)
) AS unpvt;
See the <a href="http://sqlfiddle.com/#!6/e28b4/7" rel="nofollow">fiddle here</a>.