SQL:如何进行左连接并仅匹配每个左值

问题描述 投票:0回答:1

这类问题让我感到困惑。

我有2个带有货币值的表,我必须从另一个表中找到匹配的值。如果第一个表有一个值(例如10)三次而第二个表有2次,那么我想要的结果需要显示匹配的2个值,并且一个是不匹配的。这是一个多对多的问题。

我在Google Doc https://docs.google.com/document/d/198ZiSGhR6wC2FWNc5Bcr5DTDjx3jCycFq9qlj-eQsEo/edit?usp=sharing中概述了这个问题

并在SQL Fiddle中实现它,包括各种失败的尝试。 http://sqlfiddle.com/#!17/80353/1

我更喜欢Postgres,但是通用的SQL解决方案会很好。有人可以帮忙吗?

sql postgresql
1个回答
1
投票

使用窗口函数row_number和完全连接

select a.id_a, coalesce(a.value, b.value), b.id_b
from
(
    select *, row_number() over (partition by value order by id_b) rn
    from b
) b
full join
(
    select *, row_number() over (partition by value order by id_a) rn
    from a
) a on b.value = a.value and
       b.rn = a.rn

sqlfiddle demo

© www.soinside.com 2019 - 2024. All rights reserved.