簡體   English   中英

SQL查詢 - 在小於或等於日期時加入

[英]SQL Query - join on less than or equal date

我無法弄清楚如何格式化以下查詢。 我想拿Table A並離開加入Table B 不僅在a.country = b.country而且在max start_date上小於等於join_date

Postgres(Redshift)

表A.

  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

表B.

  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

最終結果

  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

不漂亮,但直接將你的條件放在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
      );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM