sql - 使用另一个 SQL 表从一个表中进行条件选择
问题描述
我在如何设置这个动态条件选择语句时遇到了一些困难。
我把它缩减到这个基本前提:
我有两张表,表1是Cars
:
Id Serial Size
1 x99 M
2 x99 L
3 z50 M
4 x99 S
表二是一个CodeAssignment
表:
Id Serial Size Code
1 x99 L 5000
2 x99 NULL 3000
3 z50 NULL 60
我试图得到一个声明,它将拉出以下内容:
Id Serial Size Code
1 x99 M 3000
2 x99 L 5000
3 z50 M 60
4 x99 S 3000
除非有指定的大小,否则应将代码作为默认值拉出(即,在Size
上NULL
的CodeAssignment
位置),应该首选该大小。
如果我做
select * from Test..Cars c
left join Test..CodeAssignment a on c.Serial = a.Serial and c.Size = a.Size
我得到了正确的Code
但仅适用Size
于在 CodeAssignment 表中具有条目的条目。
我尝试将它附加到一个c.Size
为空的联合,但它为汽车带来了两个分配L x99
......
我玩弄了使用 CASE WHEN 但认为这只能使用硬编码值,我的问题是这应该有条件地从第二个表中提取,并且会有多个条件列进行测试。
这是否可以使用当前设置或者我如何设置表格来做这种事情?
解决方案
您可以使用两个left join
s:
select c.*, coalesce(ca.code, cad.code) as code
from cars c left join
codeassignment ca
on ca.serial = c.serial and ca.size = c.size left join
codeassignment cad
on cad.serial = c.serial and cad.size is null and ca.size is null;
这是一个 db<>fiddle。
第一个left join
是精确匹配。如果第一个不匹配,则第二个是默认值。
推荐阅读
- javascript - 从服务向控制器发出事件不会在 ng-repeat 上加载菜单
- java - java.lang.NoClassDefFoundError: org/aopalliance/aop/Advice
- google-cloud-functions - 欧洲地区仍有美国IP地址,我可以更改吗?
- vue.js - 如何在 Vue 中将逻辑分离到一个单独的组件中?
- python - 按组计算行中值之间的差异
- ffmpeg - 使用ffmpeg测量音量?
- python - Python:创建 RTF 文件时使用变量
- data-modeling - 技术初创公司使用的数据建模工具
- c# - Windows asp .net 应用程序和 Redis
- java - 在java中合并两个xml