0

Create view with fields from another table as column headers

I've got two tables that I'd like to combine into a view.

The first table contains the structure:

PhoneNumberType PhoneNumberTypeName

101 Mobile

102 Home

103 Work

The second table contains the actual data that will be stored, and the columns reference the ID of the first table:

PhoneNumberType PhoneNumber PersonId

101 90354351 1001

102 98345634 1001

103 92345123 1002

What I'd like to get as a result in a view:

Mobile Home Work PersonId

9035435 98345634 Null 1001

Null Null 92345 1002

Basically I would like to combine 2 tables and create a view.

1 Answer 1

1

You can use PIVOT in this case as following:

-- CREATING SAMPLE DATA
WITH FIRST_TABLE(PhoneNumberType, PhoneNumberTypeName)
AS
(
SELECT 101, 'Mobile' from dual union all
SELECT 102, 'Home' from dual union all
SELECT 103, 'Work' from dual
),
second_table (PhoneNumberType, PhoneNumber, PersonId)
AS
(
select 101, 90354351, 1001 from dual union all
select 102, 98345634, 1001 from dual union all
select 103, 92345123, 1002 from dual
)
--
-- ACTUAL QUERY STARTS FROM HERE
SELECT
    *
FROM
    (
        SELECT
            S.PERSONID,
            S.PHONENUMBER,
            F.PHONENUMBERTYPENAME
        FROM
            FIRST_TABLE F
            JOIN SECOND_TABLE S ON F.PHONENUMBERTYPE = S.PHONENUMBERTYPE
    ) PIVOT (
        MAX ( PHONENUMBER )
        FOR PHONENUMBERTYPENAME
        IN ( 'Mobile',
        'Home',
        'Work' )
    )
ORDER BY
    1

db<>fiddle demo

Cheers!!

Sign up to request clarification or add additional context in comments.

2 Comments

You can also use listagg instead of max in case someone has two mobile numbers.
@ponderstibbons, I can. But it depends on the requirement of questioner. And yes, good idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.