gpt4 book ai didi

sql - 如何编写将电话号码从列转换为单列的 SQL 查询?

转载 作者:行者123 更新时间:2023-12-02 19:01:29 25 4
gpt4 key购买 nike

如何编写将电话号码从列转换为单个列的 SQL 查询。假设有多个 personID,每个 personID 最多有 3 个电话类型:Primary、Secondary 和 Tertiary。目前,对于每个人,他们都列在三个单独的列中。

期望的结果是电话号码全部位于一列中,另一列包含电话类型

当前数据

<表类=“s-表”><标题>Person_ID主要_电话Secondary_PhoneTertiary_Phone <正文>1222111111155511111119991111111222211111125551111112999111111232221111113555111111399911111134222111111455511111149991111114

所需数据

<表类=“s-表”><标题>Person_ID电话号码电话类型 <正文>12221111111主要15551111111中学19991111111高等教育22221111112主要25551111112中学29991111112高等教育32221111113主要35551111113中学39991111113高等教育42221111114主要45551111114中学49991111114高等教育

最佳答案

在 Oracle 12c 版本中,您可以使用交叉应用将列逆透视为行:

select t.person_id, x.*
from mytable t
cross apply (
select primary_phone as phone_number, 'Primary' as phone_type from dual
union all select secondary_phone, 'Secondary' from dual
union all select tertiary_phone, 'Tiertiary' from dual
) x

在早期版本中,您可以使用union all:

select person_id, primary_phone as phone_number, 'Primary' as phone_type from mytable
union all select person_id, secondary_phone, 'Secondary' from mytable
union all select person_id, tertiary_phone, 'Tiertiary' from mytable

关于sql - 如何编写将电话号码从列转换为单列的 SQL 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65514759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com