如何根据多个日期组合获取值

时间:2014-09-12 10:30:37

标签: sql sql-server sql-server-2008 overlap

我必须检索一个对帐单结算周期的兴趣值,这些兴趣值每天都会有所不同。 更清楚:

我有一个表[APPLICABLEINTEREST],其中有[兴趣]列。这个[兴趣]值的变化取决于另外两列[EFFECTIVEFROMDATE]和[EFFECTIVETODATE]。

让我们举个例子:

[interest] =10% [EFFECTIVEFROMDATE] = sep 1st 2014 [EFFECTIVETODATE] = sep 15th 2014.

[interest] = 20% [EFFECTIVEFROMDATE] = sep 16th 2014 [EFFECTIVETODATE] = sep 30th 2014

[interest] = 30% [EFFECTIVEFROMDATE] = oct 1st 2014 [EFFECTIVETODATE] = null (this means for remaining dates)

现在我必须在声明期间检索这些值。

对于ex1:如果我的陈述期间在sep 1和sep 30之间,我必须检索10%和20%

表示ex2:如果我的陈述期间是在sep17th到oct 15th之间,我必须检索20%和30%

我尝试以下代码:

 declare @Fromdate date='2014-08-10'
 declare @Todate date='2014-09-14'

select [iinterest] from APPLICABLEINTEREST where (EFFECTIVEFROMDATE >=@Fromdate and EFFECTIVETODATE<=@Todate)
  Or
 (EFFECTIVEFROMDATE <=@Fromdate and EFFECTIVETODATE<=@Todate)
 Or
 (EFFECTIVEFROMDATE <=@Fromdate and EFFECTIVETODATE>=@Todate)
 Or
 (EFFECTIVEFROMDATE >=@Fromdate and EFFECTIVETODATE>=@Todate)
 Or
 (EFFECTIVEFROMDATE >=@Fromdate and EFFECTIVETODATE<=@Todate)

但这不起作用,因为它不适合所有条件。

任何帮助?提前谢谢

编辑:

declare @Fromdate date='2014-09-01'
declare @Todate date='2014-10-30'

select DAILYAPPLICABLEINTERESTRATE from LOCAPPLICABLEINTEREST where
@Fromdate between EFFECTIVEFROMDATE and EFFECTIVETODATE or @Todate between EFFECTIVEFROMDATE and EFFECTIVETODATE

当我的利率为

时,这会跳过

sep1st将15作为.75   sep16到oct1为.95   10月2日至10月30日为.99

对于这些值,上面的查询返回.75和.99(它跳过.95,因为它在sep01和oct 30之间失败了)

1 个答案:

答案 0 :(得分:1)

以下是我要做的基本知识:

create table APPLICABLEINTEREST (iinterest decimal, EFFECTIVEFROMDATE date,EFFECTIVETODATE date)
insert into APPLICABLEINTEREST
values 
(10, '2014-09-1', '2014-09-15')
, (20, '2014-09-16', '2014-09-30')
, (30, '2014-10-1', '9999-12-31')

create table DATES (D_DATE date)
go

-- filling sample dates
with xDAYS as (
    SELECT TOP (2000) n = ROW_NUMBER() OVER (ORDER BY [object_id]) FROM sys.all_objects
)
insert into DATES
select D_DATE from (select CONVERT(DATE, DATEADD(DAY, n, '2013-12-30')) as D_DATE from xDAYS) d
ORDER BY D_DATE

declare @Fromdate date='2014-09-10'
declare @Todate date='2014-10-14'

select EFFECTIVEFROMDATE, EFFECTIVETODATE, iinterest, count(*) as number_of_days from APPLICABLEINTEREST a
inner join DATES d on d.D_DATE between EFFECTIVEFROMDATE and EFFECTIVETODATE
where d.D_DATE between @Fromdate and @Todate
group by EFFECTIVEFROMDATE, EFFECTIVETODATE, iinterest

那是:

  • 有一个“日历”表(DATES)(用于真实世界的利息计算需要工作日标志等)
  • 将其加入利率表(APPLICABLEINTEREST

编辑:

或者,对于期间内非常基本的利率选择:

select iinterest from APPLICABLEINTEREST 
 where @Todate >= EFFECTIVEFROMDATE and @Fromdate < EFFECTIVETODATE