SQL join against date ranges?

后端 未结 6 1558
故里飘歌
故里飘歌 2020-12-05 00:57

Consider two tables:

Transactions, with amounts in a foreign currency:

     Date  Amount
========= =======
 1/2/2009    1500
 2/4/         


        
6条回答
  •  时光取名叫无心
    2020-12-05 01:13

    SELECT 
        a.tranDate, 
        a.Amount,
        a.Amount/a.Rate as convertedRate
    FROM
        (
    
        SELECT 
            t.date tranDate,
            e.date as rateDate,
            t.Amount,
            e.rate,
            RANK() OVER (Partition BY t.date ORDER BY
                             CASE WHEN DATEDIFF(day,e.date,t.date) < 0 THEN
                                       DATEDIFF(day,e.date,t.date) * -100000
                                  ELSE DATEDIFF(day,e.date,t.date)
                             END ) AS diff
        FROM 
            ExchangeRates e
        CROSS JOIN 
            Transactions t
             ) a
    WHERE a.diff = 1
    

    The difference between tran and rate date is calculated, then negative values ( condition b) are multiplied by -10000 so that they can still be ranked but positive values (condition a always take priority. we then select the minimum date difference for each tran date using the rank over clause.

提交回复
热议问题