2013-02-13 95 views
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/201002/11/2010的利率为4.25,如在行23中所见,但从03/11/2010开始,它是4.5%。如何编写使用月和年来查找平均利率的SQL查询(使用TSQL)?

感谢

+0

我想你应该为这个场景添加一些统计知识,然后查找TSQL过程。 – Kalanamith 2013-02-13 04:35:14

回答

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

+0

一个很酷的解决方案。 – Kalanamith 2013-02-13 04:47:30

+0

与sytax的一些小问题,但一旦修复它的作品。我还没有更彻底地测试它,但我认为它应该是好的。谢谢@Gordon。 – mlevit 2013-02-13 05:29:37