简体   繁体   English

在 DB2 SQL 中获取键的记录但显示单独键的值

[英]Get record for a key but display value for a separate key in DB2 SQL

So I have a table which has a composite primary key for SHIP# & REF#.所以我有一个表,其中包含 SHIP# 和 REF# 的复合主键。 Each SHIP# has two codes for REF# which are BM and PO.每个 SHIP# 有两个 REF# 代码,即 BM 和 PO。 BM field is mandatory but the PO field only gets populated when the user actually inputs something. BM 字段是强制性的,但 PO 字段仅在用户实际输入内容时才会填充。 So, a basic select would display something like this:因此,基本的 select 将显示如下内容:

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

Now, you will notice that shipment 000004 has only BM and no PO.现在,您会注意到货件 000004 只有 BM,没有 PO。

I want to display all shipments with PO's values.我想显示所有带有 PO 值的货件。 So, if the PO value is empty or doesn't exist like in case '000004', it should simply put '-'.因此,如果 PO 值为空或不存在(如“000004”),则应简单地输入“-”。 Since the BM is mandatory you'll have to get all records where BM exists but display value of the PO field.由于 BM 是强制性的,您必须获取 BM 存在但显示 PO 字段值的所有记录。

So, the output should be:所以,output 应该是:

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

Let me know if you need more clarifications.如果您需要更多说明,请告诉我。 Thanks.谢谢。

You can use aggregation:您可以使用聚合:

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

This returns the value as NULL -- which seems like a very good choice.这将返回NULLvalue ——这似乎是一个非常好的选择。 If you really want '-' , then use COALESCE() :如果您真的想要'-' ,请使用COALESCE()

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

An outer join against itself can do the job too.针对自身的外部连接也可以完成这项工作。 For example:例如:

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'

Result:结果:

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

See running example at db<>fiddle .请参阅db<>fiddle的运行示例。

EDIT - Find only BMs with no PO.编辑 - 只查找没有 PO 的 BM。

You can use the same query and add the extra predicate and b.ship is null in it, as in:您可以使用相同的查询并添加额外的谓词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

Result:结果:

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

See running example at db<>fiddle .请参阅db<>fiddle的运行示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM