Presuming that each CUSTOMER#
is uniquely associated to a single CUSTOMERNAME
, a scalar subquery should be all that is required to generate the expected results.
Below is an example.
First create the test table:
CREATE TABLE CUSTOMER(
CUSTOMER# NUMBER,
CUSTOMERNAME VARCHAR2(64),
REPAYCUSTOMER# NUMBER,
LOAN# NUMBER
);
And load the test data:
INSERT INTO CUSTOMER VALUES (123, 'John Doe',456,1);
INSERT INTO CUSTOMER VALUES (456, 'Jane Doe',456,2);
INSERT INTO CUSTOMER VALUES (123, 'John Doe',123,3);
Then run query:
SELECT
CUSTOMER.CUSTOMER#,
CUSTOMER.CUSTOMERNAME,
CUSTOMER.REPAYCUSTOMER#,
CUSTOMER.LOAN#,
(SELECT DISTINCT REPAYCUSTOMER.CUSTOMERNAME
FROM CUSTOMER REPAYCUSTOMER
WHERE REPAYCUSTOMER.CUSTOMER# = CUSTOMER.REPAYCUSTOMER# ) AS REPAYCUSTOMER
FROM CUSTOMER;
Result:
CUSTOMER# CUSTOMERNAME REPAYCUSTOMER# LOAN# REPAYCUSTOMER
123 John Doe 456 1 Jane Doe
456 Jane Doe 456 2 Jane Doe
123 John Doe 123 3 John Doe
But please note if there are ambiguities in the unique association between CUSTOMER#
and CUSTOMERNAME
(For example if the first customer# 123 were John Doe
and the second 123 wereChewbacca
) this query will (and should) fail.
If the dependency between CUSTOMERNAME
and CUSTOMER#
are consolidated
the need need for DISTINCT
here is alleviated.
If possible, it might be worth considering alternative designs to the provided table--this can help make fetches like this reliable, and can help in maintaining the integrity of the data (as well as in constraining the hierarchical relationships between rows).