簡體   English   中英

左聯接具有邏輯/條件

[英]Left join with logic / condition

我的頭銜有點模棱兩可,但我會在下面嘗試澄清。

我創建了一個具有幾個聯接的視圖(A)。 我正在嘗試將該視圖與另一個視圖(B)合並。 這兩個視圖都包含年份字段,公司ID,行業ID以及一個叫I或U的產品代碼。

視圖B還包含員工ID,實際上每個公司ID都有多個員工ID。 任何員工ID的產品代碼都可以是I,U或兩者。 如果兩者兼有,則產品代碼會區分兩個相同的員工ID。

現在,我想加入關於年份,客戶ID,行業ID和產品代碼的視圖A。 但是,由於視圖B中的每個客戶ID可能出現兩次(如果該客戶的基礎員工同時具有產品代碼I和U),我只想加入一次。

這是產品代碼的客戶ID的分布:

我不是U:165'370

你而不是我:45'27

你和我:48'920

left join [raw].[ViewA] a on a.year=b.year and a.CustomerID=b.CustomerID
and a.IndustryID=b.IndustryID and a.ProductCode ='I' 

這是我目前正在使用的聯接,盡管我排除了CustomerID僅具有產品代碼U的所有記錄。之所以我只希望每個Customer ID / Year / IndustryID僅聯接一次是因為我以后從視圖A聚合其他一些值。因此,我不能讓該值出現兩次。

當前結果

Year CustomerID IndustyID ProductCode Value
2015    A         Z           I         50
2015    A         Z           U         NULL
2015    B         Z           I         40
2016    A         Z           I         20
2016    B         Z           U         NULL

我想要什么

Year CustomerID IndustyID ProductCode Value
2015    A         Z           I         50
2015    A         Z           U         NULL
2015    B         Z           I         40
2016    A         Z           I         20
2016    B         Z           U         30

如果我理解正確,請嘗試以下操作

[偽]

left join ( Select *, rank() over (partition by whatMakesItUnique Order by ProductCode) distinction From tableA ) a
    on your conditions + a.distinction = 1

這樣的想法是,如果對ProductCode“ I”的whatMakesItUnique有2行,則分配數字1;如果只有1行,則給“ U”分配數字1,然后加入該分配的數字

在您的情況下,“ whatMakesItUnique”可能是列Year,CustomerID,IndustyID。

我認為您可以使用外部應用程序執行您想要的操作:

outer apply
(select top (1) a.*
 from [raw].[ViewA] a 
 where a.year = b.year and a.CustomerID = b.CustomerID and
       a.IndustryID = b.IndustryID 
 order by (case a.ProductCode when 'I' then 1 when 'U' then 2 else 3 end)
) a

這將從ViewA返回一行,按產品代碼優先。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM