Horizontally Stretching a Table in SQL

20 Views Asked by At

I have this table:

CREATE TABLE table_a (
    name_1 VARCHAR(255),
    name_2 VARCHAR(255),
    year INT,
    var1 VARCHAR(255),
    var2 INT
);

INSERT INTO table_a (name_1, name_2, year, var1, var2) VALUES
    ('john', 'sally', 2010, 'a', 1),
    ('john', 'sally', 2011, 'b', 3),
    ('kevin', NULL, 2005, 'b', 4),
    ('jack', 'beth', 2010, 'a', 2),
    ('jack', 'beth', 2011, 'a', 1),
    ('jack', NULL, 2012, 'b', 3),
    ('sally', 'john', 2010, 'c', 5),
    ('sally', 'john', 2011, 'a', 2),
    ('sally', NULL, 2015, 'd', 3),
    ('beth', 'jack', 2010, 'e', 4),
    ('beth', 'jack', 2011, 'a', 1),
    ('beth', 'henry', 2013, 'f', 1);

It looks like this:

 name_1 name_2 year var1 var2
   john  sally 2010    a    1
   john  sally 2011    b    3
  kevin   NULL 2005    b    4
   jack   beth 2010    a    2
   jack   beth 2011    a    1
   jack   NULL 2012    b    3
  sally   john 2010    c    5
  sally   john 2011    a    2
  sally   NULL 2015    d    3
   beth   jack 2010    e    4
   beth   jack 2011    a    1
   beth  henry 2013    f    1

Here is what I am trying to accomplish:

  • I want to add two new columns to this table: var1_other, var2_other
  • For pairs of (name_1, name_2) that are in the same year (e.g. john, sally, 2010 ... sally, john, 2010), I want to take the other pair's values of var1 and var1 and populate it in the newly created columns (i.e. var1_name_other, var2_name_other)
  • When this is not possible, I want to leave insert NULL values

The final result should look like this (sample):

name_1 name_2 year var1 var2 var1_other var2_other
   john  sally 2010    a    1          c          5
   john  sally 2011    b    3          a          2
  kevin   NULL 2005    b    4       NULL       NULL
#etc

Here is what I tried so far:

WITH 
my_table_swapped AS (
  SELECT name_2 AS name_1, name_1 AS name_2, year, var1 AS var1_other, var2 AS var2_other
  FROM my_table
),

my_table_final AS (
  SELECT a.name_1, a.name_2, a.year, a.var1, a.var2, b.var1_other, b.var2_other
  FROM my_table a
  LEFT JOIN my_table_swapped b ON a.name_1 = b.name_1 AND a.name_2 = b.name_2 AND a.year = b.year
)

SELECT name_1, name_2, year, var1, var2,
       COALESCE(var1_other, 'NULL') AS var1_other,
       COALESCE(var2_other, 'NULL') AS var2_other
FROM my_table_final;

Is this the correct way to do this??

0

There are 0 best solutions below