[英]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
語法。 一些使用limit
或select top
或其他一些方法。
我也不確定是否需要子查詢中的where
子句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.