获取一个键的记录,但在DB2SQL中显示一个单独键的值

2j4z5cfb  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(242)

所以我有一个表,它有一个ship#&ref#的复合主键。每艘船有两个参考代码,即bm和po。bm字段是必需的,但po字段只有在用户实际输入某些内容时才会填充。因此,一个基本的选择将显示如下内容:

SHIP#           REF#    VALUE
000002          BM      20001836                      
000002          PO      020                           
000003          BM      20001834                      
000003          PO      8-694                         
000004          BM      20001835

现在,您会注意到000004号货物只有bm,没有po。
我想用采购订单的值显示所有发货。因此,如果po值是空的或者不存在,比如案例'000004',它应该简单地放'-'。因为bm是必需的,所以您必须获取bm存在的所有记录,但显示po字段的值。
所以,输出应该是:

SHIP#           REF#    VALUE                     
000002          PO      020                           
000003          PO      8-694                         
000004          PO      -

如果你需要更多的澄清,请告诉我。谢谢。

svgewumm

svgewumm1#

外部连接本身也可以完成这项工作。例如:

select a.ship, 'PO' as ref, coalesce(b.value, '-') as value
from t a
left join t b on b.ship = a.ship and b.ref = 'PO'
where a.ref = 'BM'

结果:

SHIP    REF  VALUE
------  ---  -----
000002  PO   020
000003  PO   8-694
000004  PO   -

参见db<>fiddle上的运行示例。
编辑-仅查找没有采购订单的bms。
您可以使用相同的查询并添加额外的 predicate and b.ship is null 在它里面,比如:

select a.ship, 'PO' as ref, coalesce(b.value, '-') as value
from t a
left join t b on b.ship = a.ship and b.ref = 'PO'
where a.ref = 'BM' 
  and b.ship is null

结果:

SHIP    REF  VALUE 
------- ---- ----- 
000004  PO   -

参见db<>fiddle上的运行示例。

chhqkbe1

chhqkbe12#

可以使用聚合:

select ship#, 'PO' as ref#,
       max(case when ref# = 'PO' then value end) as value 
from t
group by ship#

这将返回 value 作为 NULL --看起来是个不错的选择。如果你真的想 '-' ,然后使用 COALESCE() :

select ship#, 'PO' as ref#,
       coalesce(max(case when ref# = 'PO' then value end), '-') as value 
from t
group by ship#

相关问题