SQL将所有行合并到一列中-无连接

SQL将所有行合并到一列中-无连接,sql,pivot,converter,transpose,unpivot,Sql,Pivot,Converter,Transpose,Unpivot,我有一个表,我需要有多行,我把他们都放在一个新的表 我的所有行都需要转换为一行 +-------+-----------+-------+--------+ | ID | Name | Last | Gender | +-------+-----------+-------+--------+ | 1 | Person1 | Last1 | M | | 2 | Person2 | Last2 | F | | 3 | Perso

我有一个表,我需要有多行,我把他们都放在一个新的表

我的所有行都需要转换为一行

+-------+-----------+-------+--------+
| ID    |   Name    |  Last | Gender |
+-------+-----------+-------+--------+
|  1    | Person1   | Last1 |   M    |
|  2    | Person2   | Last2 |   F    |
|  3    | Person3   | Last3 |   M    |
|  4    | Person4   | Last4 |   F    |
+-------+-----------+-------+--------+
我需要将上表转换为下表:

  +-------+------------+------------+
| 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
联合快乐解决方案

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

最常用的方法是使用
联合所有

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;

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

最常用的方法是使用
联合所有人

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;

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

用您正在使用的数据库标记您的问题。用您正在使用的数据库标记您的问题。感谢所有回答此问题的人!!!我在这里呆了一会儿。感谢所有回答这个问题的人!!!我在这里呆了一会儿。