【发布时间】:2012-08-26 09:15:15
【问题描述】:
我正在尝试编写两个表之间的连接,其中左表中的日期值落入右表的时隙。因此,例如,如果我有:
TABLE A TABLE B
ID TIMESTMP ID TIMESMTP VALUE
1 8/31/2012 2:00 PM 1 8/30/2012 4:00 AM A
2 8/29/2012 3:00 PM 1 8/31/2012 1:00 PM B
3 7/04/2012 5:00 AM 1 8/31/2012 3:00 PM C
2 8/20/2012 1:00 PM A
结果应该是:
TABLE C
ID TIMESTMP VALUE
1 8/31/2012 2:00 PM B
2 8/29/2012 3:00 PM A
3 7/04/2012 5:00 AM null
我想在表B中找到对应的记录,最大时间戳仍然是
谢谢!
更新
这是我按照 Gordon Linoff 的建议使用 lead() 的解决方案:
SELECT b.value, a.*
FROM table_a a
LEFT OUTER JOIN (
SELECT id, timestmp,
lead(timestmp) over(PARTITION BY id ORDER BY timestmp) AS next_timestmp,
value FROM table_b
) b
ON a.id = b.id
AND (a.timestmp >= b.timestmp AND (a.timestmp < b.timestmp OR b.timestmp IS NULL))
【问题讨论】: