mysql - 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
解决方案
您可以使用以下方法执行此操作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;
推荐阅读
- sql - 带有内部连接的postgresql更新查询
- amazon-s3 - Tableau + S3:通过 tableau 从 S3 存储桶下载文件
- java - 强制设置者到一个类。在测试方法中填充值
- python - 将字典添加到现有键值时出现此错误的问题
- javascript - 在本地托管 jQuery 会导致动画计数器关闭一个数字
- excel - 删除所有具有自动填充值的行
- c++ - 关于继承的棘手 C++ 代码输出的问题
- facebook - 缺少“将 Messenger 添加到您的网站”部分
- python - 正则表达式和删除括号
- python - 将某些 pandas 数据框列值从一列移动到另一列,并用 Nan 替换旧位置