Skip to content
Advertisement

How to merge more than two select queries to single result set in oracle

I need to merge the result set of four queries into single result output.

Example:

Select sum(marks) total from table1 Where id > 1000 and id < 2000
Select sum(marks) total1 from table1 where id =>2000
Select sum(tables) totaltbl from table2 where id > 1000 and id < 2000
Select sum(tables) totaltbl1 from table2 where id => 2000

I need the output in the below format

Total total1 totaltbl totaltbl1
100.  2000.   10.      30

Advertisement

Answer

One option would be applying Conditional Aggregation during joining of the tables :

SELECT SUM(CASE WHEN t1.id >  1000 AND t1.id < 2000 THEN t1.marks END ) "Total",
       SUM(CASE WHEN t1.id >= 2000 THEN t1.marks END ) "Total1",
       SUM(CASE WHEN t2.id >  1000 AND t2.id < 2000 THEN t2.tables END ) "Totaltbl",
       SUM(CASE WHEN t2.id >= 2000 THEN t2.tables END ) "Totaltbl1"
  FROM table1 t1
 CROSS JOIN table2 t2     
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement