2012-09-10 20 views
0
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山坳ttl_new關口,而我得到一個錯誤,當我用動態的名字,但如果僅僅是兩個和功能的全部內容粘貼到它的第三個總和功能。所以只是想知道這是否可能,它肯定會更容易閱讀。Oracle - 可能在sum函數中使用別名?

這是Oracle 8i的

+0

[有一種方法可以在where子句中使用計算字段?](http://stackoverflow.com/questions/3884678/there-is-a-way-to-use-a-calculated -field-in-the-where-clause) –

+0

在SQL中,整個select子句在邏輯上同時進行評估。查詢優化器必須選擇一個特定的順序來執行評估,但是結果必須發生,因爲if_所有列都是一次計算的。因此,任何一列的輸入都不會在其他列中提供。 –

+0

想了一下,我不認爲這個問題是一個完全重複的問題鏈接。解決方案是一樣的,使用內聯視圖,但原因是不同的。不同子句的邏輯順序,與'select'子句中的邏輯順序。 –

回答

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 

我也修復了你的連接語法。