如何在第一天映射2表条件

时间:2015-12-01 00:59:45

标签: google-bigquery

我有2个包含列的表,如下所示:

表A

key_a, date_a
 'k1', '2015-11-25'
 'k2', '2015-11-10'
 'k3', '2015-10-09'

表B

id, key_b, date_b
 1, 'k1',  '2015-10-01'
 2, 'k1',  '2015-11-02'
 3, 'k1',  '2015-11-25'
 4, 'k2',  '2015-10-15'
 5, 'k2',  '2015-11-09'
 6, 'k3',  '2015-09-15'
 7, 'k3',  '2015-10-02'
 8, 'k3',  '2015-10-08'

我想找到表B中的行date_b首先使用相同的key_b

key_a, date_a,       id, date_b 
 'k1', '2015-11-25', 1,  2015-10-01
 'k2', '2015-11-10', 5,  2015-11-09
 'k3', '2015-10-09', 6,  2015-09-15

我该怎么做?

1 个答案:

答案 0 :(得分:1)

快速 - 应该工作

SELECT
  key_a, date_a, b.id AS id, b.date_b AS date_b
FROM table_a AS a
JOIN (
  SELECT 
    id, key_b, date_b,
    ROW_NUMBER() OVER(PARTITION BY key_b ORDER BY date_b) AS num
  FROM table_b
) AS b
ON a.key_a = b.key_b
WHERE b.num = 1