问题描述
我有一个包含 30 列的表,我想轻松地取消透视所有列.我知道我可以使用这个策略:
I have a table with 30 columns and I want to easily unpivot ALL columns. I understand I can use this strategy:
SELECT col, value
INTO New_Table
FROM
(SELECT * FROM Test_Data) p
UNPIVOT
(value FOR col IN (Column_Name1, Column_Name2... Column_Name30)) as unpvt
我的数据是这样进来的:
This is how my data comes in:
Column_Name1 Column_Name2 Column_Name3
Value11 Value21 Value31
Value12 Value22 Value32
Value13 Value23 Value33
这就是我想将它存储在新表中的方式:
This is how I want to store it in the new table:
New_Column1 New_cloumn2
Column_Name1 Value11
Column_Name1 Value12
Column_Name1 Value13
Column_Name2 Value21
...
但一定有比输入 30 个列名更简单的方法.
But there must be an easier way than typing in the 30 column names.
提前致谢.
推荐答案
这似乎是一个损坏的数据模型,但您可以避免输入列列表.
This seems like a broken data model, but you can avoid typing out lists of columns.
您可以使用它来生成列列表:
You can use this to generate a list of columns:
SELECT name
FROM sys.columns
WHERE objecT_id = OBJECT_ID('Test_Data')
还有:
DECLARE @List VARCHAR(MAX) = STUFF((SELECT DISTINCT ',' + QUOTENAME(name)
FROM sys.columns
WHERE objecT_id = OBJECT_ID('Test_Data')
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)')
,1,1,'')
PRINT @List
然后您可以在动态 sql 语句中使用该列表:
You can then use that list in a dynamic sql statement:
DECLARE @List VARCHAR(MAX) = STUFF((SELECT DISTINCT ',' + QUOTENAME(name)
FROM sys.columns
WHERE objecT_id = OBJECT_ID('Test_Data')
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)')
,1,1,'')
,@sql VARCHAR(MAX)
SET @sql = 'SELECT col,value
INTO New_Table
FROM (SELECT * FROM Test_Data) p
UNPIVOT (value FOR col IN ('+@List+')) as unpvt
'
EXEC (@sql)
我建议在使用 EXEC
之前使用 PRINT (@sql)
以确保动态查询是您所追求的.
I suggest using PRINT (@sql)
before using EXEC
to ensure the dynamic query is what you were after.
这篇关于取消透视 SQL 表中的所有列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!