SQL 所有行合并为一列 - 不串联

SQL all rows into one column - no concatenation

我有一个 table,我需要它有多行,我将它们全部放入一个新的 table。

我所有的行都需要转换成一行。

+-------+-----------+-------+--------+
| ID    |   Name    |  Last | Gender |
+-------+-----------+-------+--------+
|  1    | Person1   | Last1 |   M    |
|  2    | Person2   | Last2 |   F    |
|  3    | Person3   | Last3 |   M    |
|  4    | Person4   | Last4 |   F    |
+-------+-----------+-------+--------+

我需要将上面的table转换成下面的:

  +-------+------------+------------+
| NewID | ColumnName |    Value   |
+-------+------------+------------+
|     1 | ID         |    1       |
|     1 | Name       |    Person1 |
|     1 | Last       |    Last1   |
|     1 | Gender     |    M       |
|     2 | ID         |    2       |
|     2 | Name       |    Person2 |
|     2 | Last       |    Last2   |
|     2 | Gender     |    F       |
|     3 | ID         |    3       |
|     3 | Name       |    Person3 |
|     3 | Last       |    Last3   |
|     3 | Gender     |    M       |
|     4 | ID         |    4       |
|     4 | Name       |    Person4 |
|     4 | Last       |    Last4   |
|     4 | Gender     |    F       |
|       |            |            |
+-------+------------+------------+

联盟开心解决

select 'id' as columnname, id as value from table
union all
select 'name' as columnname, name as value  from table
union all
.e
.t
.c

最通用的方法是使用union all:

select 'id' as columnname, cast(id as varchar(255)) as value from t union all
select 'name', name as value from t union all
select 'last', last as value from t union all
select 'gender', gender as value from t;

这基本上适用于任何数据库,尽管转换为字符串可能会有所不同。一些数据库提供其他更有效的解决方案。