Re: Limitting full join to one match

From: "Phil Endecott" <spam_from_pgsql_lists(at)chezphil(dot)org>
To: "John W Higgins" <wishdev(at)gmail(dot)com>
Cc: <pgsql-general(at)lists(dot)postgresql(dot)org>
Subject: Re: Limitting full join to one match
Date: 2018-12-06 15:43:12
Message-ID: 1544110992364@dmwebmail.dmwebmail.chezphil.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general pgsql-hackers

John W Higgins wrote:
> On Wed, Dec 5, 2018 at 4:34 PM Phil Endecott <
> spam_from_pgsql_lists(at)chezphil(dot)org> wrote:
>
>> Dear Experts,
>>
>> I have a couple of tables that I want to reconcile, finding rows
>> that match and places where rows are missing from one table or the
>> other:
>>
>> ...
>
>
>> So my question is: how can I modify my query to output only two rows,
>> like this:?
>>
>> +------------+--------+------------+--------+
>> | date | amount | date | amount |
>> +------------+--------+------------+--------+
>> | 2018-01-01 | 10.00 | 2018-01-01 | 10.00 |
>> | 2018-02-01 | 5.00 | | |
>> | | | 2018-03-01 | 8.00 |
>> | 2018-04-01 | 5.00 | 2018-04-01 | 5.00 |
>> | 2018-05-01 | 20.00 | 2018-05-01 | 20.00 | 1
>> | 2018-05-01 | 20.00 | 2018-05-01 | 20.00 | 2
>> +------------+--------+------------+--------+
>>
>>
> Evening Phil,
>
> Window functions are your friend here. I prefer views for this stuff - but
> subqueries would work just fine.
>
> create view a_rows as (select *,
> row_number() OVER (PARTITION BY date, amount) AS pos
> from a);
> create view b_rows as (select *,
> row_number() OVER (PARTITION BY date, amount) AS pos
> from b);
>
> select
> a_rows.date,
> a_rows.amount,
> a_rows.pos,
> b_rows.date,
> b_rows.amount,
> b_rows.pos
> from
> a_rows full join b_rows using (date,amount,pos);

Thanks John, that's great. I'm a little surprised that there isn't an
easier way, but this certainly works.

Regard, Phil.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Ron 2018-12-06 15:45:22 n_mod_since_analyze
Previous Message Adrian Klaver 2018-12-06 15:30:18 Re: postgis after pg_upgrade

Browse pgsql-hackers by date

  From Date Subject
Next Message Phil Endecott 2018-12-06 15:46:30 Re: Limitting full join to one match
Previous Message Robert Haas 2018-12-06 15:25:58 Re: zheap: a new storage format for PostgreSQL