1
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 函数的全部内容粘贴到第三个 sum 函数中作品。所以只是想知道这是否可能,它肯定会更容易阅读。

这适用于 Oracle 8i

4

1 回答 1

1

大多数数据库的范围规则不允许您在同一 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

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

于 2012-09-10T14:47:34.393 回答