如何使用SQL减去值

时间:2014-04-08 17:19:22

标签: sql oracle

你能告诉我怎样才能减去数值?

SQL>

select SUM(bytes/1024/1024) from dba_data_files where TABLESPACE_NAME='UNDOTBS1'

2;

SUM(BYTES/1024/1024)
--------------------
            7000

SQL>

select SUM(BYTES/1024/1024) from DBA_UNDO_EXTENTS where STATUS LIKE 'ACTIVE';

SUM(BYTES/1024/1024)
--------------------
               8

我需要获得7000 - 8的值

当我这样做时

select SUM(bytes/1024/1024) from dba_data_files where TABLESPACE_NAME='UNDOTBS1'
minus
select SUM(BYTES/1024/1024) from DBA_UNDO_EXTENTS where STATUS='ACTIVE';

我只从第一个选择中获得结果。

4 个答案:

答案 0 :(得分:5)

在此使用双伪表并将总和计算为标量:

SELECT 
   (SELECT SUM(bytes/1024/1024) as sum_a 
    from dba_data_files where TABLESPACE_NAME='UNDOTBS1')
 - (select SUM(BYTES/1024/1024) as sum_b 
    from DBA_UNDO_EXTENTS where STATUS LIKE 'ACTIVE') as Difference
FROM
    dual;

答案 1 :(得分:1)

可能会工作:

SELECT sum_a-sum_b as result
FROM
    (SELECT SUM(bytes/1024/1024) as sum_a from dba_data_files where TABLESPACE_NAME='UNDOTBS1') as a, 
    (select SUM(BYTES/1024/1024) as sum_b from DBA_UNDO_EXTENTS where STATUS LIKE 'ACTIVE') as b

答案 2 :(得分:0)

的语法
SELECT ...
minus
SELECT...

正在使用集合数学方法。它从集合[7000]中减去集合[8],留下集合[7000]。其他答案为您提供了解决此问题并获取所需信息的选项。

答案 3 :(得分:0)

另一种方法:

select (SUM(u.bytes) - SUM(a.BYTES)) /1024/1024
from dba_data_files u
   cross join DBA_UNDO_EXTENTS a
where u.TABLESPACE_NAME='UNDOTBS1'
   and a.STATUS='ACTIVE';