Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining two select queries from the same table

The table contains an ID column, valueHeading column and a value column. I want to separate the value column into two new columns called valueHeading1 and valueHeading2 depending on which type of valueHeading the value has.

So I want to join this select: Edit: Full join

SELECT ID
      ,valueHeading
      ,value as 'valueHeading1'
FROM table1
WHERE valueHeading = 'valueHeading1'

With This select:

SELECT ID
      ,value as 'valueHeading2'
FROM table1
WHERE valueHeading = 'valueHeading2'

on their respective ID's. How do I do this?

Edit to illustrate what I want to do:

Original table:

ID    valueHeading    value
0     valueHeading1    a
0     valueHeading2    a
1     valueHeading1    ab
1     valueHeading2    NULL
2     valueHeading1    abcd
2     valueHeading2    abc

New Table:

ID    valueHeading1    valueHeading2
0          a               a
1          ab              NULL
2         abcd             abc
like image 749
mdc Avatar asked Feb 01 '13 14:02

mdc


People also ask

How do I merge two queries in the same table in SQL?

Use the UNION ALL clause to join data from columns in two or more tables. In our example, we join data from the employee and customer tables. On the left of the UNION ALL keyword, put the first SELECT statement to get data from the first table (in our example, the table employee ).

How do I join the same table with different conditions in SQL?

You can think of a self join as a join between two copies of the same table. For each record with a non-null value in spouse_id , we search for the value of customer_id that matches it. When we find a match, the columns firstname and lastname are added to the resulting table. Table aliases are required in a self join.


1 Answers

Try something like :

SELECT ID
      , CASE WHEN valueHeading = 'valueHeading1' THEN value ELSE NULL END AS valueHeading1
      , CASE WHEN valueHeading = 'valueHeading2' THEN value ELSE NULL END AS valueHeading2
FROM table1
WHERE valueHeading IN ('valueHeading1', 'valueHeading2')

If you want to regroup all values on one row for each ID, you can try :

SELECT ID
      , MAX(CASE WHEN valueHeading = 'valueHeading1' THEN value ELSE NULL END) AS valueHeading1
      , MAX(CASE WHEN valueHeading = 'valueHeading2' THEN value ELSE NULL END) AS valueHeading2
FROM table1
WHERE valueHeading IN ('valueHeading1', 'valueHeading2')
GROUP BY ID
HAVING MAX(CASE WHEN valueHeading = 'valueHeading1' THEN value ELSE NULL END) IS NOT NULL
OR MAX(CASE WHEN valueHeading = 'valueHeading2' THEN value ELSE NULL END) IS NOT NULL

See SQLFiddle. I also tried on Oracle 11g and MSSQL 2012, and it works each time.

like image 144
xlecoustillier Avatar answered Oct 03 '22 16:10

xlecoustillier