簡體   English   中英

Oracle-可以在sum函數中使用別名嗎?

[英]Oracle - Possible to use alias in sum function?

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函數的全部內容粘貼到3rd sum函數中,作品。 因此,只要想知道這是否可行,它肯定會更容易閱讀。

這是針對Oracle 8i

大多數數據庫的作用域規則不允許您在同一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

我還修復了您的連接語法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM