2

我有下表:

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到 the02/11/2010的利率4.25如行中所示,23但从03/11/2010后面开始是4.5百分比。如何编写使用月份和年份来查找平均利率的 SQL 查询(使用 TSQL)?

谢谢

4

1 回答 1

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具有加权平均值的计算。

于 2013-02-13T04:41:35.977 回答