Skip to content
Advertisement

Add rows to SQL table based on a list of values

So I have a table like this and an attribute list – ('attr1', 'attr2', 'attr3').

id | attr_name | attr_value
----------------------------
 1 |   attr1   |  val1 
 1 |   attr2   |  val2
 1 |   attr3   |  val3 
 2 |   attr1   |  val1
 2 |   attr2   |  val4

I want to make a query where this table can be “expanded” to be the following and then make a query using it.

id | attr_name | attr_value
----------------------------
 1 |   attr1   |  val1 
 1 |   attr2   |  val2
 1 |   attr3   |  val3 
 2 |   attr1   |  val1
 2 |   attr2   |  val4
 2 |   attr3   |  null

The attribute list is given to me and dynamic.

Advertisement

Answer

Cross join the IDs and the attribute names and then left join the table to get the attribute values or NULL if no match was found.

SELECT x1.id,
       x2.attr_name,
       t2.attr_value
       FROM (SELECT DISTINCT
                    t1.id
                    FROM elbat t1) x1
            CROSS JOIN (VALUES ('attr1'),
                               ('attr2'),
                               ('attr3')) x2 (attr_name)
            LEFT JOIN elbat t2
                      ON t2.id = x1.id
                         AND t2.attr_name = x2.attr_name
       ORDER BY x1.id,
                x2.attr_name;                     
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement