How do I stack the first two columns of a table into a single column?

故事扮演 提交于 2019-12-25 00:33:22

问题


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')


回答1:


You need unpivot:

SELECT Id, Code, Other
FROM 
   Source
UNPIVOT
   (Code FOR code_ IN 
      (code_1, code_2)
) AS unpvt;

See the fiddle here.



来源:https://stackoverflow.com/questions/48313904/how-do-i-stack-the-first-two-columns-of-a-table-into-a-single-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!