关于日期的SQL连接查询

时间:2014-01-27 17:49:07

标签: sql outer-join

我有一张表A

ID   Settle Date
 1     1/15/2013
 2     2/15/2013

和表B为

ID     From           Rate 
 1   1/1/2013          1.5
 1   2/1/2013          2
 2   1/1/2013          4
 2   2/1/2013          5

我想要一个加入,以便我得到

ID   Settle Date   Rate
 1    1/15/2013     1.5
 2    2/15/2013      5

基本上,想要获得适用于该日期的费率。请指教

1 个答案:

答案 0 :(得分:2)

在您的加入中使用BETWEEN

select
    a.ID 
    SettleDate,
    Rate
FROM TableA a
INNER JOIN TableB b
  ON a.SettleDate BETWEEN b.From AND b.To
  AND a.ID = b.ID

确定调整“小”变化(不小):

select
    a.ID 
    SettleDate,
    Rate
FROM TableA a
INNER JOIN TableB b
  ON a.ID = b.ID
  AND b.[From] = (SELECT MAX([From]) FROM TableB WHERE ID = a.ID AND From <= a.SettleDate)