如果不存在该项目,则打印“无”

时间:2019-05-10 09:48:48

标签: sql oracle

我想运行一个SQL查询,其中我只有很少的项目及其类型,例如RENT,LEASE或PURCHASE。问题在于某些项目可能有也可能没有全部三个,而是其中任何一个或两个。但是,如果某项没有特定类型,我想返回NONE而不是Blank。

我当前的查询是:

select DISTINCT ITEM_ID,  UOM, LIST_PRICE from PRICELIST_TABLE
where item_id IN ('XYZ')
and PRICELIST_HDR in (select Pricelist_Hdr_Key from SMCFS93.YPM_PRICELIST_HDR where PRICELIST_NAME IN ('ALL') and SELLER_ORGANIZATION_CODE IN ('20'))

如何确保即使不存在特定类型的物品,我也不会得到任何帮助。例如

ITEM_ID   UOM        PRICE     
ITEMX     PURCHASE   0
ITEMX     RENT       NONE  # none if not exist

2 个答案:

答案 0 :(得分:1)

使用cross join生成行,然后使用left join引入所需的值:

with pl as (
      select DISTINCT ITEM_ID, UOM, LIST_PRICE
      from PRICELIST_TABLE
      where item_id IN ('XYZ') and
            PRICELIST_HDR in (select Pricelist_Hdr_Key
                              from SMCFS93.YPM_PRICELIST_HDR
                              where PRICELIST_NAME IN ('ALL') and
                                     SELLER_ORGANIZATION_CODE IN ('20')
                             )
      )
select i.item_id, u.uom, pl.list_price
from (select distinct item_id from pl) i cross join
     (select 'RENT' as uom from dual union all
      select 'LEASE' as uom from dual union all
      select 'PURCHASE' as uom from dual
     ) u left join
     pl
     on pl.item_id = i.item_id and pl.uom = u.uom;

cross join创建所有项目和您关心的uom类别的组合。 left join然后输入您想要的数据。

如果您要使用字符串'NONE'而不是NULL,则需要考虑类型。如果LIST_PRICE是字符串,则没问题:

coalesce(list_price, 'NONE') as list_price

如果没有,则需要转换值:

coalesce(to_char(list_price), 'NONE') as list_price

答案 1 :(得分:0)

使用coalesce()

select DISTINCT ITEM_ID,  UOM, coalesce(to_char(LIST_PRICE),'None')
from PRICELIST_TABLE left join SMCFS93.YPM_PRICELIST_HDR 
on PRICELIST_HDR =Pricelist_Hdr_Key and PRICELIST_NAME ='ALL' 
and SELLER_ORGANIZATION_CODE ='20'
where item_id ='XYZ'