0

I'm using sqlite through the RSQLite package in R.

I have two tables: Table 1 has important columns 'PERMCO' and 'Reporting_Period'. ('Reporting_Period' is an integer date)

Table 2 has important columns 'PERMCO' and 'date'. ('date' is an integer date)

I want to do a left join with table 1 as the left table. Thing is that 'PERMCO' is not unique (row-wise, many duplicates) in the second table.

For a given row of table 1, I want the match from the second table to be the row from table 2 with matching PERMCO that is closest in absolute date to 'Reporting_Period' in the first table.

Not really sure how to do this...

Thank you

4

1 回答 1

0

Idea 是一个相关子查询,用于从 table1 中的 Reporting_Period 获取 table2 中最近的一天

SELECT t1.*, t2.*
FROM table1 t1
LEFT JOIN table2 t2
ON t1.permco = t2.permco
WHERE ABS(t2."date" - t1.Reporting_Period) = (SELECT MIN(ABS("date" - t1.Reporting_Period) )
                                  FROM table2 
                                  WHERE permco = t1.permco
                                  )
     OR t2.permco IS NULL --because you want a left join
;

我不熟悉 Sqlite,因此您可能需要更改查询以减去两个日期。

于 2016-10-27T05:54:18.857 回答