Oracle - 可以在sum函数中使用别名吗?

时间:2012-09-10 14:41:14

标签: sql oracle sum

SELECT c.customer_name,
        sc.customer_id,
        SUM(
                (nvl(sc.year_1_new, 0) + nvl(sc.year_2_new, 0) + nvl(sc.year_3_new, 0) + 
                nvl(sc.year_4_new, 0) + nvl(sc.year_5_new, 0)) * sc.suggested_net
            ) AS ttl_new,
        SUM(
                (nvl(sc.year_1_nl, 0) + nvl(sc.year_2_nl, 0) + nvl(sc.year_3_nl, 0) + 
                nvl(sc.year_4_nl, 0) + nvl(sc.year_5_nl, 0)) * sc.suggested_net
            ) AS ttl_exist,
        SUM(ttl_new - ttl_exist) AS ttl_delta
FROM scenario_customers sc,
        customers c
WHERE sc.scenario_id = 10
        AND sc.customer_id = c.customer_id
GROUP BY sc.customer_id,
        c.customer_name
ORDER BY c.customer_name

我希望能够从ttl_exist col中减去ttl_new col,并且当我使用动态名称时出现错误,但是如果只是将两个sum函数的全部内容粘贴到第3个和函数它的工作原理。所以只是想知道这是否可能,它肯定更容易阅读。

这适用于Oracle 8i

1 个答案:

答案 0 :(得分:0)

大多数数据库的作用域规则不允许您在同一SELECT语句中使用别名。您可以使用子查询执行此操作:

select c.customer_name, sc.customer_id, ttl_new, ttl_exist, (ttl_new - ttl_exist) as ttl_delta
from (SELECT c.customer_name, sc.customer_id,
             SUM((nvl(sc.year_1_new, 0) + nvl(sc.year_2_new, 0) + nvl(sc.year_3_new, 0)  + nvl(sc.year_4_new, 0)  + nvl(sc.year_5_new, 0)) * sc.suggested_net) AS ttl_new, 
             SUM((nvl(sc.year_1_nl, 0) + nvl(sc.year_2_nl, 0) + nvl(sc.year_3_nl, 0) + nvl(sc.year_4_nl, 0) + nvl(sc.year_5_nl, 0)) * sc.suggested_net) AS ttl_exist
      FROM scenario_customers sc join
           customers c
           on sc.customer_id = c.customer_id
      WHERE sc.scenario_id = 10 
      GROUP BY sc.customer_id, c.customer_name
     ) t
ORDER BY c.customer_name

我还修复了你的连接语法。