在联合之后只返回一条记录
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在联合之后只返回一条记录相关的知识,希望对你有一定的参考价值。
将SQL接口用于AS / 400(iSeries)DB2数据库,但运行并发布托盘信息可以存储在两个表中的位置,一个用于未分配的库存(warpall)
,另一个用于分配的库存(warpalq)
。我需要在适用的情况下从两个表中返回记录。
warpalq
只有少数几个与warpall
有关的领域我需要从warpall
获得的一个领域也被用来加入另一个表格,warpalq
没有相关领域。
我正在使用union
从一个结果集中的两个表中返回数据,然后加入其他表。
问题是,当在结果集上加入第三个表(warcmdt)
时,它在commpm
和fdsccd
字段中具有空值/ 0,因为它在相应的表中没有数据。
有没有办法让commpm
和fdsccd
回到第2行的结果集?交联将是pal#pm = pal#pq
,因此存在相对联系。
在下面运行SQL会返回此结果集。
select
clntwf, commpm, fdsccd, clsqwf, pal#wf, dtcdpm, clsswf, srb#pm, descsc,
cor#or
from
(select substr(warpall.clntpm,1,2) as clntwf, pal#pm as pal#wf, commpm,
substr(warpall.clsspm,1,2) as clsswf, warpall.clsqpm * 1 as clsqwf, srb#pm,
dtcdpm, srd#pm
from warpall
where
locnpm <> 'ASSEMBLED PALLET'
and commpm <> 'ASSEMBLED PALLET'
and clsqpm <> 0
and clntPM <> 'D2'
and pal#pm = '1005609592'
union all
select substr(clntpq,1,2) as clntwf, pal#Pq as pal#wf, '0',
substr(clsspq,1,2) as clsswf, clsqpq * 1 as clsqwf, '0', '0', '0'
from warpalq
where
clsqpq <> 0
and clntPQ <> 'D2'
and pal#pq = '1005609592'
) as t9
left outer join warcmdt as t3
on
t3.clntcd = t9.clntwf and t3.commcd = t9.commpm
left join
warclss as t4
on
t4.clsssc = t9.clsswf
left join
warohrh as t5
on
t5.clntor = t9.clntwf
and t5.srn#or = t9.srd#pm
order by pal#wf asc
您可以尝试使用这样的公用表表达式(CTE):
with
pal (clntwf, pal#wf, commpm, clsswf, clsqwf,
srb#pm, dtcdpm, srd#pm) as (
select
substr(warpall.clntpm,1,2) as clntwf,
warpall.pal#pm as pal#wf,
warpall.commpm,
substr(warpall.clsspm,1,2) as clsswf,
warpall.clsqpm * 1 as clsqwf,
warpall.srb#pm,
warpall.dtcdpm,
warpall.srd#pm
from warpall
where
warpall.locnpm <> 'ASSEMBLED PALLET'
and warpall.commpm <> 'ASSEMBLED PALLET'
and warpall.clsqpm <> 0
and warpall.clntPM <> 'D2'
and warpall.pal#pm = '1005609592'),
alc (clntwf, pal#wf, commpm, clsswf, clsqwf,
srb#pm, dtcdpm, srd#pm) as (
select
substr(warpalq.clntpq,1,2) as clntwf,
warpalq.pal#Pq as pal#wf,
pal.commpm,
substr(warpalq.clsspq,1,2) as clsswf,
warpalq.clsqpq * 1 as clsqwf,
'0',
'0',
pal.srd#pm
from warpalq
join pal
on waarpalq.pal#pq = pal.pal#wf
where
warpalq.clsqpq <> 0
and warpalq.clntPQ <> 'D2'
and warpalq.pal#pq = '1005609592')
select
clntwf, commpm, fdsccd, clsqwf, pal#wf, dtcdpm, clsswf, srb#pm, descsc, cor#or
from
(select *
from pal
union all
select *
from alc
) as t9
left outer join warcmdt as t3
on t3.clntcd = t9.clntwf
and t3.commcd = t9.commpm
left join warclss as t4
on t4.clsssc = t9.clsswf
left join warohrh as t5
on t5.clntor = t9.clntwf
and t5.srn#or = t9.srd#pm
order by pal#wf asc
这使您可以在多个地方重复使用pal
CTE而无需重新定义它。这意味着你可以将它加入alc
CTE以获得commpm
,后来用于加入t9
和warcmdt
。现在你不应该得到那个null。我还将srd#pm
带到alc
的warpall
CTE,因为它用于t9
和warohrh
之间的连接。如果这不正确,您可以在pal.srd#pm
CTE中用'0'
替换alc
。
以上是关于在联合之后只返回一条记录的主要内容,如果未能解决你的问题,请参考以下文章
oracle中如何只查询一条复合条件的记录,即查到一条记录就返回?
oracle中如何只查询一条复合条件的记录,即查到一条记录就返回