2017-05-14 53 views
1

我知道這可能是一個簡單的問題,但我在過去的一個小時裏一直在困擾着這個問題,我不確定哪些術語可以準確地描述我正在嘗試做什麼。在SQL中如何使用多個case語句?

我正在使用Oracle 12C數據庫的應用程序,我想在這個語句中使用多個案例的相同領域,例如。 INVC_TYPE= 0,2。第一種情況:如果它的2然後是QTY*-1,並且情況2:如果它的0然後是regular並且如果它的0然後return

所以請有任何人能幫助我:

select 
t.ITEM_SID, 
i.SBS_NO as INVC_SBS, 
i.STORE_NO as INVCSTORENO, 
s.STORE_NO as STORENO, 
s.STORE_CODE as STORECODE, 
s.STORE_NAME, 
i.INVC_NO, 
i.CREATED_DATE, 
i.INVC_SID, 
i.INVC_TYPE, 
i.CASHIER_ID, 
to_char(i.CREATED_DATE) as INVCDATE, 
t.ORIG_PRICE as INVCORIGPRICE, 
t.PRICE as INVCPRICE, 
t.COST as INVCCOST, 
case 
when i.INVC_TYPE=2 then t.QTY*-1 
else t.QTY 
end as INVCQTY 
case when i.INVC_TYPE=0 then i.INVC_TYPE="REGULAR" 
case when i.INVC_TYPE=2 then i.INVC_TYPE="RETURN" 
else 'NA' 
end as INVCTYPE 
from invoice i, invc_item t, SBS_STORE_LIST s 
where 
INVC_TYPE in (0,2) and 
i.invc_sid = t.invc_sid and 
i.STORE_NO = s.STORE_NO and 
i.REF_INVC_SID is null; 

回答

1

試試這個:

select t.ITEM_SID, 
    i.SBS_NO as INVC_SBS, 
    i.STORE_NO as INVCSTORENO, 
    s.STORE_NO as STORENO, 
    s.STORE_CODE as STORECODE, 
    s.STORE_NAME, 
    i.INVC_NO, 
    i.CREATED_DATE, 
    i.INVC_SID, 
    i.INVC_TYPE, 
    i.CASHIER_ID, 
    to_char(i.CREATED_DATE) as INVCDATE, 
    t.ORIG_PRICE as INVCORIGPRICE, 
    t.PRICE as INVCPRICE, 
    t.COST as INVCCOST, 
    case 
     when i.INVC_TYPE = 2 then t.QTY * - 1 
     else t.QTY 
     end as INVCQTY, 
    case 
     when i.INVC_TYPE = 0 then i.INVC_TYPE = 'REGULAR' 
     when i.INVC_TYPE = 2 then i.INVC_TYPE = 'RETURN' 
     else 'NA' 
     end as INVCTYPE 
from invoice i 
join invc_item t on i.invc_sid = t.invc_sid 
join SBS_STORE_LIST s on i.STORE_NO = s.STORE_NO 
where INVC_TYPE in (0, 2) 
    and i.REF_INVC_SID is null; 

另外,還要注意在基礎連接部位逗號明確聯接語法。總是使用這種語法,因爲這是現代和清晰的。

+0

抱歉地說,它的顯示同樣的錯誤,遺漏的關鍵字? –

+0

@AbdulazizHasanAldabbagh - 已更新 – GurV

1

這些是您的代碼的問題,首先。

  1. 2個case語句之間缺少逗號。
  2. 您在同一列中兩次使用case關鍵字。
  3. THEN部分情況下,您正在分配一個值。您應該只返回一個值
  4. 不是一個錯誤,但你應該使用正確的聯接語法

    select t.ITEM_SID, 
        i.SBS_NO as INVC_SBS, 
        i.STORE_NO as INVCSTORENO, 
        s.STORE_NO as STORENO, 
        s.STORE_CODE as STORECODE, 
        s.STORE_NAME, 
        i.INVC_NO, 
        i.CREATED_DATE, 
        i.INVC_SID, 
        i.INVC_TYPE, 
        i.CASHIER_ID, 
        to_char(i.CREATED_DATE) as INVCDATE, 
        t.ORIG_PRICE as INVCORIGPRICE, 
        t.PRICE as INVCPRICE, 
        t.COST as INVCCOST, 
        case 
         when i.INVC_TYPE = 2 
          then t.QTY * - 1 
         else t.QTY 
         end as INVCQTY, 
        case i.INVC_TYPE 
         when 0 then 'REGULAR' 
         when 2 then 'RETURN' 
         else 'NA' 
         end as INVCTYPE 
    from invoice i 
    join invc_item t 
        on i.invc_sid = t.invc_sid 
    join SBS_STORE_LIST s 
        on i.STORE_NO = s.STORE_NO 
    where INVC_TYPE in (0, 2) 
        and i.REF_INVC_SID is null;