按日期获取平均值(缺少日期)

时间:2013-02-13 04:27:28

标签: sql sql-server tsql

我有下表:

Interest Rate ID    Interest Rate   Interest Rate Start Date
20                  3.5             2009-12-02 00:00:00.000
21                  3.75            2010-03-03 00:00:00.000
22                  4               2010-04-07 00:00:00.000
23                  4.25            2010-05-05 00:00:00.000
24                  4.5             2010-11-03 00:00:00.000
25                  4.25            2011-11-02 00:00:00.000

正如您可以看到Interest Rate跨越一个月到下一个月。我需要计算整个月的平均利息。

我们假设选择2010-1101/11/2010 02/11/2010的{​​{1}}利率为4.25,如行23所示,但从03/11/2010起,其费率为4.5%。如何编写使用月份和年份来查找平均利率的SQL查询(使用TSQL)?

由于

1 个答案:

答案 0 :(得分:1)

这是一种痛苦,所以我希望没有一个错误的错误:

select sum(((case when end_date > lastdt then lastdt else end_date end) -
            (case when start_date < firstdt then firstdt else start_date end)
           )* t.rate) /
       sum((case when end_date > lastdt then lastdt else end_date end) -
           (case when start_date < firstdt then firstdt else start_date end)
          )
from (select t.*,
             (select top 1 start_date - 1 from t t2 where t2.start_date > t.start_date order by t2.start_date
             ) as end_date
      from t
     ) t cross join
     (select cast('2011-11-01' as date) as firstdt, cast(2011-11-30) as lastdt
where firstdt <= t.end_date and lastdt >= t.start_date

这个想法是计算每个利率有效的天数。然后,平均值是速率除以天数的天数之和。

这有点复杂。内部查询为每条记录输入结束日期。 where子句只选择重叠的子句。 select计算了加权平均值。

相关问题