首页 > 解决方案 > SQL Join 表 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。

谁能帮我?

期望的输出:

COMPANY - STORE - CODE  - VALUE
  A        ASG     H    - 100    
  A        ASG     S    -  0
  A        BSG     S    - 200
  A        CSG     H    -  0
  A        CSG     S    - 100

标签: mysqlsql

解决方案


您可以使用以下方法执行此操作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;

推荐阅读