如何在SQL中使用多个case语句?

时间:2017-05-14 14:44:19

标签: sql oracle

我知道这可能是一个简单的问题,但过去一小时我一直对此感到困惑,并且不确定要查找哪些条款可以准确描述我想要做的事情。

我正在使用Oracle 12C DB的应用程序,我想在此语句中使用多个案例用于相同的字段,例如。 INVC_TYPE= 0,2。第一种情况:如果其2然后QTY*-1,则情况为2:如果其0然后是regular,如果是0return

所以请有人可以帮助我:

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;

2 个答案:

答案 0 :(得分: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;

另外,请注意显式连接语法以代替基于逗号的连接。始终使用此语法,因为它更现代,更清晰。

答案 1 :(得分:1)

首先是您的代码存在的问题。

  1. 两个案例陈述之间缺少逗号。
  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;