在SQL查询中执行union或其他命令时,我想计算列值的总和

在SQL查询中执行union或其他命令时,我想计算列值的总和,sql,oracle,Sql,Oracle,SQL>从型号为“1005”的PC中选择价格 2工会 3从型号为“3003”的打印机中选择价格 ​ 价格 谢谢你,先生, 这是我的sql代码。但我不知道如何计算这些值的和。 在这种情况下,如何计算值的总和? 请帮助我..您需要一个外部sql,其中包含以下值之和: select sum(price) form ( select price from PC where model = '1005' union select price from Printer where model = '3003

SQL>从型号为“1005”的PC中选择价格

2工会

3从型号为“3003”的打印机中选择价格

​ 价格

谢谢你,先生, 这是我的sql代码。但我不知道如何计算这些值的和。 在这种情况下,如何计算值的总和?
请帮助我..

您需要一个外部sql,其中包含以下值之和:

select sum(price) form (
select price from PC where model = '1005'
union
select price from Printer where model = '3003') as x
你不要联盟!!!这将删除重复项,因此如果价格恰好相同,您将无法获得正确的值。你希望所有人都团结起来

一种方法是将查询移动到FROM子句并使用聚合:

select sum(price)
from ((select price from PC where model = '1005'
      ) union all
      (select price from Printer where model = '3003'
      )
     ) p;
对于两个标量值,也可以只添加它们:

select ( (select price from PC where model = '1005') +
         (select price from Printer where model = '3003')
      )
from dual;
当然,如果其中一个丢失,那么在本例中结果将为NULL

select ( (select price from PC where model = '1005') +
         (select price from Printer where model = '3003')
      )
from dual;