-2

I have two tables, both of which have a date field. What I want as an end result is a table of dates (can be duplicated) with records A and B in that row.

id_a     date_a
1        Jan 1
2        Feb 2
3        Feb 2
4        Mar 3
id_b     date_b
a        Jan 1
b        Feb 2
c        Mar 3
d        Mar 3
date     id_a    id_b
Jan 1      1       a
Feb 2      2       b
Feb 2      3       null
Mar 3      4       c
Mar 3      null    d

I currently have this solution, but instead of the null fields, it would duplicate id_a : 4 and id_b : b.

SELECT 
COALESCE(Table1.date_a, Table2.date_b) AS date

Table1.id_a, 
Table2.id_b

FROM Table1
FULL OUTER JOIN Table2
  ON Table1.date_a = Table2.date_b;
Dave
  • 5

1 Answers1

0

DBFIDDLE

I added a match on the row_number of the date:

SELECT  
   COALESCE(a.date_a, b.date_b) AS date,
   a.id_a,
   b.id_b
FROM 
   (SELECT
       id_a,
       date_a,
       ROW_NUMBER() OVER(PARTITION BY date_a ORDER BY id_a) R
   FROM table1) a
FULL OUTER JOIN
   (SELECT
       id_b,
       date_b,
       ROW_NUMBER() OVER(PARTITION BY date_b ORDER BY id_b) R
   FROM table2) b ON a.date_a = b.date_b and a.R = b.R

output:

date id_a id_b
2021-01-01 1 a
2021-02-02 2 b
2021-02-02 3
2021-03-03 4 c
2021-03-03 d
Luuk
  • 12,245
  • 5
  • 22
  • 33