SQL查询 - 在小于或等于日期时加入

时间:2014-03-14 19:01:32

标签: mysql sql date join

我无法弄清楚如何格式化以下查询。我想要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}}

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
      );