带日期的SQL连接

带日期的SQL连接,sql,join,Sql,Join,我有表A和列: customer_id, month, amount customer_id, plan_id, start_date, end_date 月份类似于2015/12/01,意味着它是2015年12月支付的金额 然后是带有列的表B: customer_id, month, amount customer_id, plan_id, start_date, end_date 这是关于特定客户何时开始和结束使用特定计划的信息。当前计划的结束日期为空。一个客户过去可能会使用许多不同

我有表A和列:

customer_id, month, amount
customer_id, plan_id, start_date, end_date
月份类似于2015/12/01,意味着它是2015年12月支付的金额

然后是带有列的表B:

customer_id, month, amount
customer_id, plan_id, start_date, end_date
这是关于特定客户何时开始和结束使用特定计划的信息。当前计划的结束日期为空。一个客户过去可能会使用许多不同的计划

我需要通过连接这两个表将
plan\u id
列添加到表A中,但我不知道如何处理日期


请注意,对于每个客户,一个月只能对应一个计划。因此,即使计划的开始日期为2015/11/02,也应仅适用于下个月(2015/12/01)。

这基本上是一个连接,但不平等:

select a.*, b.*
from a left join
     b
     on a.customer_id = b.customer_id and
        a.month >= b.start_date and
        (a.month <= b.end_date or b.end_date is null);
选择a.*,b*
从左连接
B
在a.customer\u id=b.customer\u id和
a、 月份>=b.开始日期和
(a.工作一个月后,只需将“>”替换为“