Search code examples
sqlentity-attribute-value

Convert from an EAV table in SQL


Im having issues converting to format of an EAV table to something useful. The link table is confusing me and I dont really know how to start fixing this. Anyone have suggestions?

Contacts table

con_id Name Data
1      email [email protected]
2      phone 123
3      email [email protected]
4      phone 456

Link table (maps actual user accounts to rows in the Contacts table):

acct_id con_id
1       1
1       2
2       3
2       4

END GOAL:

acct_id Email       Phone
1       [email protected] 123
2       [email protected] 456

Solution

  • http://sqlfiddle.com/#!4/7cf20/5/0

    CREATE TABLE Contacts
        (con_id int, Name varchar2(5), Data varchar2(11))
    ;
    
    INSERT ALL 
        INTO Contacts (con_id, Name, Data)
             VALUES (1, 'email', '[email protected]')
        INTO Contacts (con_id, Name, Data)
             VALUES (2, 'phone', '123')
        INTO Contacts (con_id, Name, Data)
             VALUES (3, 'email', '[email protected]')
        INTO Contacts (con_id, Name, Data)
             VALUES (4, 'phone', '456')
    SELECT * FROM dual
    ;
    
    CREATE TABLE Link
        (acct_id int, con_id int)
    ;
    
    INSERT ALL 
        INTO Link (acct_id, con_id)
             VALUES (1, 1)
        INTO Link (acct_id, con_id)
             VALUES (1, 2)
        INTO Link (acct_id, con_id)
             VALUES (2, 3)
        INTO Link (acct_id, con_id)
             VALUES (2, 4)
    SELECT * FROM dual
    ;
    

    Query -

    select * from (
    select acct_id, name, Data
    from contacts c, Link l
    where c.con_id = l.con_id
    )
    pivot (max(Data) for name in ('email' as Email,'phone' as Phone));
    

    Output -

    ACCT_ID EMAIL         PHONE
    1       [email protected]   123
    2       [email protected]   456