查询以查找最接近的较小日期


8

我有一张房价表。每个费率都有一个有效的开始日期。(任何记录的结束日期都暗示着有效起始日期较新的记录的存在。)我还有一个带有活动的表。每个活动都发生在一个日期上。

将活动与该日期生效的汇率相匹配的最佳方法是什么?

(不幸的是,我没有能力修改数据结构,因此无法为费率添加明确的结束日期。)

rates:
StartDate Rate
9/1/2010    17.00
10/1/2010   18.70
11/1/2010   20.00

Activities:
WorkCenter  ActionDate Hours
WC1         9/30/2010   10
WC1         10/1/2010   5
WC2         10/30/2010  8
WC2         11/3/2010   9

Desired result:
Workcenter ActionDate   Hours   Rate    Cost(=rate*hours)
WC1         9/30/2010   10      17.00   170.00
WC1         10/1/2010   5       18.70    93.50
WC2         10/30/2010  8       18.70   149.60
WC2         11/3/2010   9       20.00   180.00

Answers:


11
SELECT 
    a.WorkCenter
  , a.ActionDate
  , a.Hours
  , r.Rate
  , r.Rate * a.Hours  AS Cost
FROM 
    Activities AS a
  JOIN
    Rates AS r
      ON  r.StartDate = 
          ( SELECT MAX(StartDate)
             FROM Rates 
             WHERE StartDate <= a.ActionDate
          ) ;

GROUP BY解决方案:

SELECT 
    a.WorkCenter
  , a.ActionDate
  , a.Hours
  , r.Rate
  , r.Rate * a.Hours  AS Cost
FROM 
    Activities AS a
  JOIN
    ( SELECT 
          a.ActionDate
        , MAX(r.StartDate) AS StartDate
      FROM 
          Activities AS a
        JOIN
          Rates AS r
            ON r.StartDate <= a.ActionDate
      GROUP BY a.ActionDate
    ) AS grp
      ON  grp.ActionDate = a.ActionDate
 JOIN
    Rates AS r
      ON  r.StartDate = grp.StartDate ;
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.