Oracle SUM计算的值

时间:2014-05-14 10:05:34

标签: oracle sum subquery

我正在试图弄清楚我是怎么做的,或者是否可以动态地将列中的返回值相加,以便为每条记录返回一个总值,而不必再次计算它。

查询有多个子查询,所有子查询都正确计算并返回一个整数值,我正试图找到一种方法将这些值动态添加到Total列,是否可能!?

SELECT (SELECT value FROM ....) AS NUM_1
, (SELECT value FROM ....) AS NUM_2
, (SELECT value FROM ....) AS NUM_3
, SUM(NUM_1 + NUM_2 + NUM_3) AS TOTAL
FROM DUAL;

这是我想要实现的输出:

NUM_1 | NUM_2 | NUM_3 | Total
=============================
3     | 4     | 3     | 10

2 个答案:

答案 0 :(得分:2)

with numbers as (
  SELECT (SELECT value FROM ....) AS NUM_1,
         (SELECT value FROM ....) AS NUM_2,
         (SELECT value FROM ....) AS NUM_3
  FROM DUAL;
) 
select num_1, 
       num_2, 
       num_3, 
       num_1 + num_2 + num_3 as total
from numbers;

您必须确保(SELECT value FROM ....)个查询返回完全一行,否则您将收到类似&#34的错误;单行子查询会返回多行&#34 34。

答案 1 :(得分:-1)

在双重后删除半冒号(;)然后整体运行它将起作用

以数字为(   SELECT(SELECT value FROM ....)AS NUM_1,          (SELECT value FROM ....)AS NUM_2,          (SELECT值FROM ....)AS NUM_3   来自双重 ) 选择num_1,        NUM_2,        num_3,        num_1 + num_2 + num_3为总计 来自数字;