首页 > 解决方案 > 查询根据输入和优先级过滤记录,如果不匹配,则拉出空值记录

问题描述

我的要求是根据输入参数编写一个查询来显示描述,操作。在设置 Test2 中,itm 优先于 pm,并且优先于 pf。如果没有匹配,空值设置将是默认设置。

我有一张桌子 Test1

GRP                  OP                  
----- --------------------
GRP1                 A                   
GRP1                 B                   
GRP1                 C     

表测试2

OP            ITM                  PM                   PF                         CUST DESCRIP             
------ -------------------- -------------------- -------------------- ---------- --------------------
A                                                                                   123 AB                  
C                                                                                   123 BC                  
B             I1                                                                    123 CD                  
B             I2                                                                    123 DE                  
B                                  PM1                                              123 EF                  
B                                                       PF1                         123 FG                  
B                                                                                   123 FGH   

我的输入参数是 test1.grp、test2.pm、test2.itm、test.pf

如果我的输入是 GRP=GRP1, Itm=I1, PM=PM1, PF=PF1, 我的输出应该是

op   descrip
A     AB  
C     BC  
B     CD   (because itm takes precedence over others)

如果我的输入是 GRP=GRP1, Itm=I3, PM=PM1, PF=PF1, 我的输出应该是

op   descrip  
A     AB  
C     BC  
B     EF   (because itm I3 does not exist, so next precedence is pm)

如果我的输入是 GRP=GRP1, Itm=I3, PM=PM2, PF=PF2, 我的输出应该是

op   descrip  
A     AB  
C     BC  
B     FGH   (because the three conditions do not match, so null is the generic setup)  

感谢您是否可以提供帮助,因为我无法按优先顺序比较多个记录。

标签: sqloracle

解决方案


我能够为我的要求编写查询。

`select coalesce(itmd,pmd,pfd,nulld), op from ( select a.op,
max(decode( itm,'I3' , descrip)) itmd,
max(decode( pm,'PM2' , descrip)) pmd,
max(decode( pf,'PF2' , descrip)) pfd,
max(decode(itm,null,decode(pm,null,decode(pf,null,descrip)))) nulld
  from test1 a, test2 b where a.grp='GRP1' and a.op=b.op
  group by a.op);`

谢谢


推荐阅读