我想运行一个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
答案 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'