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ある月から次の月へのスパンを見ることができます。1 か月の平均利率を計算する必要があります。

では、 を選ぶとしましょう2010-11。までの金利は行に見られる01/11/2010よう02/11/2010でしたが、それ以降はパーセントでした。月と年を使用して平均利率を求める SQL クエリ (TSQL を使用) を作成するにはどうすればよいですか?4.252303/11/20104.5

ありがとう

4

1 に答える 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 に答える