[英]SQL Join duplicating values on table A
我正在嘗試找出問題的解決方案,但到目前為止還沒有成功。
表 A:
COMPANY - STORE - CODE
A ASG H
A ASG S
A BSG S
A CSG H
A CSG S
表 B:
COMPANY - STORE - CODE - VALUE
A ASG H 100
A BSG H 200
A CSG S 100
我需要將表 B 中的“值”列一次寫入表 A,而不重復行。 如果我使用“代碼”列加入它們,我只會得到一次寫入的值,但有時連接會失敗,正如您在商店“BSG”上注意到的那樣,它的代碼是表 A 上的 S,但表 B 上的 H .
如何從表 B 中獲取僅在表 A 上寫入一次的值? 此外,有時在表 B 上,代碼最終可能是 S,而表 A 上的商店只有代碼 H。
誰能幫我?
所需的 Output:
COMPANY - STORE - CODE - VALUE
A ASG H - 100
A ASG S - 0
A BSG S - 200
A CSG H - 0
A CSG S - 100
您可以使用row_number()
執行此操作:
select a.*,
(case when row_number() over (partition by a.company, a.store, a.code order by a.company) = 1
then b.value else 0 end
end) as value
from a left join
b
on a.company = b.company and a.store = b.store and a.code = b.code
order by a.company, a.store, a.code, value desc;
使用ROW_NUMBER()
window function:
select company, store, code,
case when rn = 1 then value else 0 end value
from (
select a.*, b.value,
row_number() over (partition by a.company, a.store order by a.code = b.code desc) rn
from TableA a left join TableB b
on b.company = a.company and b.store = a.store
) t
order by company, store, code
請參閱演示。
結果:
> company | store | code | value
> :------ | :---- | :--- | ----:
> A | ASG | H | 100
> A | ASG | S | 0
> A | BSG | S | 200
> A | CSG | H | 0
> A | CSG | S | 100
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.