2

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

期望的结果是电话号码都在一个列中,而另一列有电话类型

当前数据

Person_ID 常用电话 次要电话 Tertiary_Phone
1 2221111111 5551111111 9991111111
2 2221111112 5551111112 9991111112
3 2221111113 5551111113 9991111113
4 2221111114 5551111114 9991111114

所需数据

Person_ID 电话号码 电话类型
1 2221111111 基本的
1 5551111111 中学
1 9991111111 第三
2 2221111112 基本的
2 5551111112 中学
2 9991111112 第三
3 2221111113 基本的
3 5551111113 中学
3 9991111113 第三
4 2221111114 基本的
4 5551111114 中学
4 9991111114 第三
4

2 回答 2

3

在 Oracle 开始版本 12c 中,您可以使用以下命令将列还原为行cross apply

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
于 2020-12-30T23:24:13.320 回答
2

你似乎想做一个unpivot

with p as (
  select 1 person_id, 
         '2221111111' primary_phone, 
         '5551111111' secondary_phone, 
         '9991111111' tertiary_phone
    from dual
  union all
  select 2, 
         '2221111112' primary_phone, 
         '5551111112' secondary_phone, 
         '9991111112' tertiary_phone
    from dual
)
select person_id,
       phone_number,
       phone_type
  from p
unpivot (
  phone_number
  for phone_type in (
     primary_phone as 'Primary',
     secondary_phone as 'Secondary',
     tertiary_phone as 'Tertiary'
  )
)

显示正在运行的查询的liveSQL 链接

于 2020-12-30T23:48:45.643 回答