简体   繁体   English

如何使用另一个表的行值作为列名(动态)在SQL中创建新表?

[英]How do I create a new table in SQL using the row values of another table as column names (dynamic)?

How do I create a new table in SQL using the row values of another table as column names? 如何使用另一个表的行值作为列名在SQL中创建新表? Please note the original table values are dynamic. 请注意原始表值是动态的。 Is dynamic Pivot the only option? 动态Pivot是唯一的选择吗?

For example, if my old table looks like: 例如,如果我的旧表看起来像:

players
-----------
Lebron James
Kobe Bryant
Dwayne Wade
Chris Bosh
James Harden

I want the new table to look like: 我希望新表看起来像:

Lebron James | Kobe Bryant | Dwayne Wade | Chris Bosh | James Harden

Try this example: 试试这个例子:

DROP TABLE #players 
CREATE TABLE #players (name VARCHAR(200))
INSERT INTO #players 
SELECT 'Lebron James'
UNION SELECT 'Kobe Bryant'
UNION SELECT 'Dwayne Wade'
UNION SELECT 'Chris Bosh'
UNION SELECT 'James Harden'


DECLARE @cmd VARCHAR(8000)
SET @cmd ='CREATE TABLE MyNewTable (id INT'
SELECT @cmd = @cmd + '
, ['+name+'] VARCHAR(255)'
FROM #players

SELECT @cmd = @cmd + ')'

PRINT @cmd
EXEC(@cmd)

EXEC('SELECT * FROM MyNewTable')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用列中的不同值创建表作为新表的列名? - How can I create a table using distinct values from a column as the column names for the new table? 我想在我的表中添加新行,但我想使用列名 (SQL) 进行数学运算 - I want to add new row in my table but I want to do mathematical operation using column names (SQL) 如何使用自定义列名创建新的 SQL 表并填充这些列 - How do I create a new SQL table with custom column names and populate these columns 在包含记录的现有表中,如何创建一个新的 datetime2(2) 列并使用基于另一列的值填充它? - In an existing table with records, how do I create a new datetime2(2) column and populate it with values based on another column? 如何使用 SQL 在表中创建一个新列以仅显示来自另一列的特定数据? - How can I create a new column in a table to show only specific data from another column using SQL? select如何将某行的值作为另一个表的列名? - How select a row values to be column names of another table? SQL - 如何创建一个包含值为列和新格式的表? - SQL - How do I create a table with values as columns and a new format? 如何选择行值作为另一个表的列名? - How to Select Row values as another table's column names? 如果 2 列值不存在,则在 SQL 表中插入新行数据 - Insert new row of data in SQL table if the 2 column values do not exist SQL:如何创建一个新列,其值引用另一个表中的另一个列? - SQL: How do create a new column and its value is referencing another column from another table?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM