使用表oracle上的case选择同一行中的值

时间:2016-02-01 07:52:05

标签: sql oracle case

我在oracle中有这样的表:

enter image description here

然后我想选择customer_type和我的名为'customer_id'的新列。如果customer_type为'CORPORATE',那么'customer_id'列将填充shipper_id否则如果customer_type为'RETAIL',则列('customer_id')将填充shipper_phone。

这是我的疑问:

select 
shipper_id,
shipper_name, 
customer_type,
case customer_type when 'RETAIL' then shipper_phone
when 'CORPORATE' then shipper_id
else 'Y'
from 
connote c 
inner join 
mst_customer mc 
on c.shipper_id = mc.customer_id ;

1 个答案:

答案 0 :(得分:1)

您在 CASE 声明中缺少END关键字:

SELECT shipper_id,
  shipper_name,
  customer_type,
  CASE customer_type
    WHEN 'RETAIL'
    THEN shipper_phone
    WHEN 'CORPORATE'
    THEN shipper_id
    ELSE 'Y'
  END
FROM connote c
INNER JOIN mst_customer mc
ON c.shipper_id = mc.customer_id;

同样可以使用 DECODE 编写:

SELECT shipper_id,
  shipper_name,
  customer_type,
  DECODE(customer_type, 
         'RETAIL',
          shipper_phone,
         'CORPORATE',
          shipper_id,
         'Y')
FROM connote c
INNER JOIN mst_customer mc
ON c.shipper_id = mc.customer_id;