我无法弄清楚如何格式化以下查询。我想要Table A
并离开加入Table B
。不仅在a.country = b.country
上,而且max start_date
上的join_date
也小于 ID join_date country email
----- ----------- --------- ------
124 '2013-10-03' US john@doe.com
423 '2013-04-21' CA bob@doe.com
412 '2013-03-30' US test@test.com
。
Postgres(Redshift)
表A
start_date country joined_from
------------- ----------- --------------
'2013-08-21' US google
'2014-01-02' CA yahoo
'2013-03-02' CA microsoft
'2013-02-10' US facebook
'2013-09-01' US yahoo
表B
ID join_date country email start_date joined_from
------ ----------- --------- --------- ------------ -------------
124 '2013-10-03' US john@doe.com '2013-09-01' yahoo
423 '2013-04-21' CA bob@doe.com '2013-03-02' microsoft
412 '2013-03-30' US test@test.com '2013-02-10' facebook
最终结果
{{1}}
答案 0 :(得分:3)
不漂亮,但直接将您的条件放在JOIN
中应该有效:
SELECT a.ID, a.join_date, a.country, a.email, b.start_date, b.joined_from
FROM a LEFT JOIN b ON a.country = b.country
AND b.start_date = (
SELECT MAX(start_date) FROM b b2
WHERE b2.country = a.country AND b2.start_date <= a.join_date
);