SQL根据列选择多行数据

时间:2018-11-07 10:48:37

标签: sql oracle

我想编写一个Oracle sql查询,它将按以下顺序获取数据:

NAME    Phone1  Phone2
JOHN    1123     321
RIK 11  Null
KATE    Null    21

输出:

NAME    PHONE
JOHN    1123
JOHN    321
RIK 11
KATE    21

3 个答案:

答案 0 :(得分:1)

您可以尝试使用UNION ALL

select name, phone1 as phone from tablenmae
union all
select name, phone2  from tablenmae

或者您可以尝试使用UNPVOT

select *
  from tablenmae
unpivot
(
    phone
    for val in (phone1, phone2)
)

答案 1 :(得分:0)

我们可以在此处尝试使用UNION ALL

SELECT NAME, Phone1 AS PHONE FROM yourTable WHERE Phone1 IS NOT NULL
UNION ALL
SELECT NAME, Phone2 FROM yourTable WHERE Phone2 IS NOT NULL
ORDER BY NAME, PHONE;

enter image description here

Demo

答案 2 :(得分:0)

从表1中选择名称,电话1,其中电话1不为空 工会
从table1中选择名称,phone2,其中phone2不为空