2017-02-04 179 views
1

我通常會在java中使用流行的if-else語句,但在sqlplus中,我在select語句中使用case來查詢下面的條件語句。Select語句問題?

select title, to_char(nvl2(((retail-cost)/cost)*100, 
     ((retail-cost)/cost)*100, 
     ((retail-cost)/cost)*100), '99999.99') "Margin", 
     to_char(discount, '99999.99') "Discount", 
(case when ("Margin" >= 60) then 'Very High Profit' 
     when ("Margin" >= 30) then 'High Profit' 
     else ("Margin" >= 0) then 'Loss Leader' 
     end) "Pricing Structure" 
    from books 
    order by title; 

我希望能得到像我這樣的結果,但我試圖移動排序;每次我仍然遇到錯誤。

TITLE       Margin Discount Pricing Structure 
------------------------------ -------- --------- --------------------------------- 
BIG BEAR AND LITTLE DOVE   68.23   Very high profit 
BODYBUILD IN 10 MINUTES A DAY  65.07   Very high profit 
+0

這是錯誤的方式去做 - 很難寫,讀和維護。相反,應該爲每個「定價結構」及其說明設置一個帶有閾值的小表格;只計算查詢中的邊距並加入到這個小表中。這樣,您可以非常輕鬆地添加或刪除級別,更改閾值和/或更改說明。 – mathguy

回答

4

sql除非在子查詢中才能看到別名。你應該把它寫類似:

case 
when (retail-cost/cost)*100 >= 60 then 'Very High Profit' 
when (retail-cost/cost)*100 >= 30 then 'High Profit' 
when (retail-cost/cost)*100 >= 0 then 'Loss Leader' 
else 'SOMETHING HERE' 
end "Pricing Structure" 

別的東西要考慮的是,這NVL2:

to_char(nvl2(((retail-cost)/cost)*100, 
    ((retail-cost)/cost)*100, 
    ((retail-cost)/cost)*100), '99999.99') 

什麼都不給你。爲什麼?導致nvl2(exp1,exp2,exp3)。如果exp1不爲null,則打印exp2,如果爲null,則打印exp3。不僅如此,您的NVL也不會在這裏做任何事情,因爲它總是會輸出((零售成本)/成本)* 100。你最好寫作to_char(((retail-cost)/cost)*100),'99999.99')

如果你的exp1 = exp2那麼你最好只寫NVL(exp1,exp2)。如果exp1不是null,那麼它將打印它,否則它將打印exp2。

+0

某些價值對於折扣列爲空,因此如果根本沒有折扣;它仍然會在這裏計算這((零售成本)/成本)* 100這一個。 –

+0

我覺得你讓我困惑。我在最後給出的描述是用於保證金計算。 – Jucan

+0

對不起。請忽略我之前的評論。我只記得折扣計算不包括在保證金列中。我會嘗試繞過你建議的地方,我不需要使用nvl2,只需直接進行計算。在案件中,我太分心了,我忘了那些小小的信息。 –

0

您的case語句中不能使用別名「Margin」。你可以在你的case語句喜歡用「保證金」的整個公式:

(情況(保證金的NVL聲明)> 60)

此外,一定要在你的case語句匹配相同的數據類型。所以,你不能使用to_char()> 60,因爲你正在比較一個字符到整數。

希望這可以幫助:-)

0

使用公用表表達式(CTE),從邏輯的情況下分解出的計算:

WITH CDATA AS (select title, 
         ((retail-cost)/cost)*100 AS MARGIN, 
         to_char(discount, '99999.99') AS "Discount" 
       from books) 
SELECT TITLE, 
     TO_CHAR(MARGIN, '99999.99') AS "Margin", 
     "Discount", 
     case 
     when MARGIN >= 60 then 'Very High Profit' 
     when MARGIN >= 30 then 'High Profit' 
     else MARGIN >= 0 then 'Loss Leader' 
     end AS "Pricing Structure" 
    order by title; 

好運。