取消透视 SQL 表中的所有列

Unpivot ALL Columns in a SQL Table(取消透视 SQL 表中的所有列)
本文介绍了取消透视 SQL 表中的所有列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 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 表中的所有列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)