如何根据事务日期将事务表连接到历史查找表?

时间:2013-03-06 16:52:40

标签: sql select join

我正在尝试使用事务表和历史表运行SQL查询,如下所示:

历史表:

Active Date    Inactive Date    Attribute   CustID
1/1/2013        1/15/2013         Blue         A 
1/15/2013       1/30/2013         Green        A

交易表:

Transaction Date     CustID
1/12/2013              A
1/28/2013              A

And I would want to return 

结果:

Transaction Date     CustID   Attribute 
1/12/2013              A        Blue
1/28/2013              A        Green

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:0)

JOIN上的表格可以custidtransaction dateactive date inactive date可以select t.`transaction date`, t.custid, h.attribute from transactions t inner join historical h on t.custid = h.custid and t.`transaction date` >= h.`Active Date` and t.`transaction date` <= h.`Inactive Date`

{{1}}

请参阅SQL Fiddle with Demo

答案 1 :(得分:0)

正如我看到的结果一样,date of the transaction介于历史表的Active DateinActive日期之间。结果可以通过在两个条件下加入表格来实现:它与CustID匹配,并且它在两个日期之间。

SELECT  a.*, b.Attribute
FROM    TransactionTable a
        INNER JOIN HistoricalTable b
            ON  a.CustID = b.CustID AND
                a.TransactionDATE BETWEEN b.ActiveDate AND b.InActiveDATE

要进一步了解联接,请访问以下链接: