首页 > 解决方案 > 如何将两个以上的选择查询合并到oracle中的单个结果集

问题描述

我需要将四个查询的结果集合并到单个结果输出中。

例子:

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

我需要以下格式的输出

Total total1 totaltbl totaltbl1
100.  2000.   10.      30

标签: sqloraclejoinaggregation

解决方案


一种选择是在加入表期间应用条件聚合:

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     

推荐阅读