sql - 查询根据输入和优先级过滤记录,如果不匹配,则拉出空值记录
问题描述
我的要求是根据输入参数编写一个查询来显示描述,操作。在设置 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)
感谢您是否可以提供帮助,因为我无法按优先顺序比较多个记录。
解决方案
我能够为我的要求编写查询。
`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);`
谢谢
推荐阅读
- powershell - 在远程 PC 上调用时无法解压缩文件夹
- postgresql - nginx:在 PostgreSQL 中存储 POST 数据
- python-3.x - 如何修复错误:[Errno 2] 没有这样的文件或目录:'C:\\Program Files\\Python37\\lib\\venv\\scripts\\nt\\python_d.exe'
- javascript - jQuery:如何处理自闭合标签和多个循环?
- javascript - 更改节点 js 中获取的 json 数据?
- css - Running ADF apps in Chrome vs IE
- javascript - Laravel:获取最后一个插入ID并在注册前显示它
- html - 无法在容器内使用 float-right 移动我的 div
- powerbi - Power BI 网关数据源是否忽略用于创建数据集的凭据?
- angular6 - Angular 2单选按钮ngmodel