如何将同一oraclesql表中一个查询的和减去另一个查询的和?

qij5mzcb  于 2021-07-24  发布在  Java
关注(0)|答案(4)|浏览(445)

我有两个查询,两个都返回总和,我想在一个单一的查询这些总和之间的差异。

Query 1:
   select sum(Records) from my_table where column1 ='1' and column2 = 'abc'
Query 2:
    select sum(Records) from my_table where column1 ='2' and column2 = 'adf'

注意两个查询都有相同的表名。

My table:
column1 column2  column3     column4  records
1           aa   something      abc    12
2           bb   something      acd    25
2           aa   something      adf    04
1           bb   something      abc    21

任何帮助都将不胜感激。提前谢谢。

jhiyze9q

jhiyze9q1#

我今天手头没有甲骨文,但这应该能让你接近。

select ( select sum(Records) from my_table where column1 ='1' and column2 = 'abc') -  
(select sum(Records) from my_table where column1 ='2' and column2 = 'adf') 
as Total from dual;
vtwuwzda

vtwuwzda2#

您只需将现有查询的值用作列,并取其差值。

with my_table (column1, column2, column3,column4,  records) as 
    ( select 1, 'aa', 'something', 'abc',  12   from dual union all       
      select 2, 'bb', 'something', 'acd',  25   from dual union all 
      select 2, 'aa', 'something', 'adf',  04   from dual union all 
      select 1, 'bb', 'something', 'abc',  21   from dual
    )   
select r1, r2, r1-r2 diff
  from  (select sum(Records) r1 from my_table where column1 ='1' and column4 = 'abc')
     ,  (select sum(Records) r2 from my_table where column1 ='2' and column4 = 'adf');

注意:为了匹配提供的示例日期,我将查询改为引用column4而不是column2。

z2acfund

z2acfund3#

使用条件聚合:

select sum(case when column1 = '1' and column2 = 'abc' then Records
                when column1 = '2' and column2 = 'adf' then - Records
                else 0
           end) as diff
from my_table ;
i1icjdpr

i1icjdpr4#

或者,如果要保留已编写的查询,请将它们用作CTE:

with 
a (suma) as 
  (select sum(Records) from my_table where column1 ='1' and column2 = 'abc'),
b (sumb) as
  (select sum(Records) from my_table where column1 ='2' and column2 = 'adf')
select a.suma - b.sumb as difference
from a cross join b

相关问题