select n.col1
, n.date1
, m.col2
, m.date2
from t1 n
full join t2 m on n.date1 = m.date2
and n.col1 = (select max(col1) from t1 where date1 = m.date2 )
and n.col1 is not null
where n.date1 is not null or m.date2 is not null
order by coalesce(n.date1, m.date2)
, coalesce(n.col1, m.col2)
SQL joins with order by
-
06-07-2023 - |
Question
I have two tables with
table 1
col1 date
1 13/4/2014
2 15/4/2014
3 17/4/2014
5 19/4/2014
table 2
col1 date
1 13/4/2014
3 16/4/2014
6 18/4/2014
joining the two tables i should get
col1 date col2 date
1 13/4/2014 1 13/4/2014
2 15/4/2014
3 17/4/2014 3 16/4/2014
6 18/4/2014
5 19/4/2014
the important thing is the date
columns should be sorted as can be seen for col
data 6
and 5
.
Is this possible?
EDIT :
the final table needs to be ordered by col1.date
and col2.date
such that earlier date either in col1
or col2
will be sorted in the join table 18/4/2014
will come before 19/4/2014
even if they are in different columns. I hope i am making my point clear.
Thanks
EDIT :
table 1
1, "2014-04-03"
2, "2014-04-04"
3, "2014-04-11"
4, "2014-04-16"
5, "2014-04-04"
6, "2014-04-17"
7, "2014-04-17"
table 2
1, "2014-04-04"
2, "2014-04-11"
5, "2014-04-17"
EDIT : after join it should be like
1 2014-04-03
2 2014-04-04
5 2014-04-04 1 2014-04-04
3 2014-04-11 2 2014-04-11
4 2014-04-16
6 2014-04-17
7 2014-04-17 5 2014-04-17
Solution 2
OTHER TIPS
select col1, date1, col2, date2
from
t1
full outer join
t2 on col1 = col2
order by coalesce(date1, date2), date2;
Thankfully, PostgeSQL has a wonderful function called LEAST()
; the query is then simply:
SELECT col1, date1, col2, date2
FROM t1
FULL OUTER JOIN t2
ON col1 = col2
ORDER BY LEAST(date1, date2), GREATEST(date1, date2)
(fiddle for dataset 1, fiddle for dataset 2).
EDITED
Added use of GREATEST()
to then sort by the other value.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow