首页 > 解决方案 > 使用另一个 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

除非有指定的大小,否则应将代码作为默认值拉出(即,在SizeNULLCodeAssignment位置),应该首选该大小。

如果我做

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 但认为这只能使用硬编码值,我的问题是这应该有条件地从第二个表中提取,并且会有多个条件列进行测试。

这是否可以使用当前设置或者我如何设置表格来做这种事情?

标签: sqlsql-server

解决方案


您可以使用两个left joins:

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是精确匹配。如果第一个不匹配,则第二个是默认值。


推荐阅读