SQL Server unpivot columns(SQL Server 反透视列)
问题描述
我有一个表,我想在 SQL 语句中取消透视.它由一个人和电话 1 到 5 组成.现在我正在为每部电话做一个联合,但我担心它会导致性能问题.
I have a table that I would like to unpivot in a SQL statement. It consists of a person and phone 1 through 5. Right now I'm doing a union for each phone but I fear it is causing performance issues.
列:
PERSON_GUID, 
PHONE_1, PHONE_1_VOICE_FLG, 
PHONE_2, PHONE_2_VOICE_FLG, 
PHONE_3, PHONE_3_VOICE_FLG, 
PHONE_4, PHONE_4_VOICE_FLG, 
PHONE_5, PHONE_5_VOICE_FLG
在考虑性能的情况下,我如何最好地取消透视该行,以便结果是:
How would I best unpivot the row with performance in mind so that the results are:
PERSON_GUID, PHONE_NO, VOICE_FLG
推荐答案
我更喜欢 UNPIVOT 但至于你的解决方案 -
确保您使用的是 UNION ALL 而不是 UNION.UNION ALL 只是将一个查询结果溢出另一个查询结果.UNION 消除了行重复,这是您为性能付出代价的地方.
I prefer UNPIVOT but as for your solution -
Make sure you are using UNION ALL and not UNION.
UNION ALL just spills one query result after the other.
UNION eliminates rows duplications and this is where you pay in performance.
select  PERSON_GUID,PHONE_NO,
        case right(col,1)
            when 1 then PHONE_1_VOICE_FLG
            when 2 then PHONE_2_VOICE_FLG
            when 3 then PHONE_3_VOICE_FLG
            when 4 then PHONE_4_VOICE_FLG
            when 5 then PHONE_5_VOICE_FLG
        end VOICE_FLG
from    t unpivot (PHONE_NO for col in
            (PHONE_1,PHONE_2,PHONE_3,PHONE_4,PHONE_5)) u 
                        这篇关于SQL Server 反透视列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL Server 反透视列
				
        
 
            
        - SQL 临时表问题 2022-01-01
 - 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
 - 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
 - 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
 - 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
 - 更改自动增量起始编号? 2021-01-01
 - 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
 - 在SQL中,如何为每个组选择前2行 2021-01-01
 - 导入具有可变标题的 Excel 文件 2021-01-01
 - 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
 
						
						
						
						
						
				
				
				
				