Home > Software engineering >  How to merge tables if they don't have a common column in sql?
How to merge tables if they don't have a common column in sql?

Time:02-20

Supposing I have two tables in Oracle. One of them looks like so:

Name Exam Grade
Mark Math 80
Mark English 67
Andrew Math 90
Steve English 59

The other table I have looks like this:

Mark Andrew Steve
Null Null Null

This is my expected result:

Mark Andrew Steve
Math-80 Math-90 English-59
English-67 Null Null

How would one merge the second table with the first one for it to look like the result above? My main problem is that there are no common columns, and I have to have the values of the first table set as the column names for the second table. I'm really stuck with this one...

CodePudding user response:

You can use PIVOTing along with ROW_NUMBER() Analytic function in order to group the set by each exam per each person such as

SELECT "Mark", "Andrew", "Steve"
  FROM (SELECT Name,
               Exam || '-' || Grade AS Exam,
               ROW_NUMBER() OVER(PARTITION BY Name ORDER BY Exam DESC) AS rn
          FROM t1)
 PIVOT (
        MAX(Exam) FOR Name IN ('Mark' AS "Mark",'Andrew' AS "Andrew",'Steve' AS "Steve")
       )

where the second table is not needed

Demo

CodePudding user response:

Use the AS parameter or CROSS JOIN ?

You can also read this : How join two tables using SQL without a common column

  • Related