繁体   English   中英

将来自两个表的 If/Case 连接的值插入到第三个表中

[英]insert value from join with If/Case from two tables, into a third table

所以我在创建 sql 查询时遇到了以下问题。

一个链接服务器,所以我正在使用一个开放的查询。 (编辑更新:SQL 服务器)如下图两个表:

在此处输入图像描述

我需要将值插入到第三个表中,要插入到第三个表中的值来自上面我通过 KEY ID 加入的两个表。

但是,在连接中,我想选择表 A 中的所有列,并且只选择表 B 中的值代码(表 B中的每个键 ID 有多个值代码),因此需要一个 if 或 case,具体取决于以下内容:

如果/Case Table B 的 Code = PRODUCT,选择 VALUE CODE A,

如果没有 Code=PRODUCT,则从 code = FOO 中选择 VALUE CODE,在 KEY ID 2 的情况下,这将是 VALUE CODE D。

如果给定的 Key ID 没有 Code = PRODUCT 或没有 Code = FOO,则选择对应于 Code = BAR 的 VALUE CODE,在这种情况下 Key ID 3 它将是 VALUE CODE F。

更新:有时 Foo 可以在表 B 中的 Product 之前出现,如果没有对应关系,比如没有 product、foo 或 bar 我希望在列行中返回空白。

如何以正确的方式编写这个 sql 与 if/case 连接的查询?

不确定您使用的是什么平台,但这是我在 SQL 服务器中的操作方式

SQL 服务器方法

Select a.KeyID,a.[TimeStamp],a.SalesAmount,b.ValueCode
From TableA As a
Outer Apply (
            /*This will grab the top 1 KeyID match, with the sorting you specified based on the code in TableB*/
            Select Top (1) *
            From TableB As tb
            Where a.KeyId = tb.KeyID
            And tb.Code In ('Product','Foo','Bar') /*If only want codes matching the 3 values, then include this line*/
            Order By 
                Case 
                    When tb.Code = 'Product' Then 1
                    When tb.Code = 'Foo' Then 2
                    When tb.Code = 'Bar' Then 3
                    Else 4 /*Pick any other values last*/
                End
        ) As b

在任何数据库中,您都可以使用相关子查询:

select a.*,
       (select b.valuecode
        from b
        where b.keyid = a.keyid and
              b.code in ('Product', 'Foo', 'Bar')
        order by (case code when 'Product' then 1 when 'Foo' then 2 else 3 end)
        fetch first 1 row only
       ) as valuecode
from a;

您尚未指定正在使用的数据库。 并非所有数据库都支持标准的fetch first语法。 一些使用limitselect top或其他一些方法。

我也不确定是否需要子查询中的where子句。

暂无
暂无

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

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