如何从同一个表中选择2个不同的名称并在条件上显示它们

时间:2015-11-20 17:23:18

标签: sql oracle

我有这个查询

SELECT NAME_NO
    ,(
        SELECT FNAME || ' ' || LNAME || ' ' || BIRTH_DT || ' ' || ' ' || PHONE
        FROM NAMES
        WHERE NAME_NO = 1
        ) AS "NAME1: NAME, DOB, PHONE"
    ,(
        SELECT FNAME || ' ' || LNAME || ' ' || BIRTH_DT || ' ' || ' ' || PHONE
        FROM NAMES
        WHERE NAME_NO = 2
        ) AS "NAME2: NAME, DOB, PHONE"
    ,
FROM NAMES;

我收到此错误:

01427. 00000 -  "single-row subquery returns more than one row"

我需要多条记录。

解决此问题的最佳方法是什么?

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT NAME_NO, FNAME || ' ' || LNAME || ' ' || BIRTH_DT || ' ' || ' ' || PHONE AS "NAME1: NAME, DOB, PHONE"
FROM NAMES
UNION
 SELECT FNAME || ' ' || LNAME || ' ' || BIRTH_DT || ' ' || ' ' || PHONE AS "NAME2: NAME, DOB, PHONE"
FROM NAMES
WHERE NAME_NO = 2

或者这个:

WITH N1 AS  (
        SELECT NAME_NO,FNAME || ' ' || LNAME || ' ' || BIRTH_DT || ' ' || ' ' || PHONE AS "VAL"          
        FROM NAMES          
        WHERE NAME_NO = 1),
     N2 AS (
        SELECT FNAME || ' ' || LNAME || ' ' || BIRTH_DT || ' ' || ' ' || PHONE AS "VAL"          
        FROM NAMES          
        WHERE NAME_NO = 2)
SELECT
    NAME_NO,VAL 
FROM N1,N2;

答案 1 :(得分:0)

你需要使用PIVOT。试试这个

Select A "NAME1: NAME, DOB, PHONE" , B "NAME2: NAME, DOB, PHONE" from (SELECT FNAME || ' ' || LNAME || ' ' || BIRTH_DT || ' ' || ' ' || PHONE N, NAME_NO  
        FROM NAMES)
Pivot
(Max(N) for NAME_NO  in (1 as A, 2 as B)
);