需要帮助理解一个功能

时间:2011-01-13 10:11:00

标签: sql sql-server-2005 tsql

我以前曾要求帮助编写/改进我需要根据每个月的不同值计算溢价的功能。保费分为12个月,每个月按百分比计算。因此,如果政策从三月开始,我们在jan,我们将获得10个月的价值。所以我需要将每月收入加起来给我们总收入。 wach公司每个月都会有不同的收益值。

我原来的代码是Here。它的可怕和缓慢因此请求帮助。

我看到了以下代码。代码可以工作,但是返回了很大的数字。

begin

set @begin=datepart(month,@outdate)
set @end=datepart(month,@experiencedate)

;with a as
(
    select *,
    case calmonth
        when 'january' then 1
        when 'february' then 2
        when 'march' then 3
        when 'april' then 4
        when 'may' then 5
        when 'june' then 6
        when 'july' then 7
        when 'august' then 8
        when 'september' then 9
        when 'october' then 10
        when 'november' then 11
        when 'december' then 12
        end as Mnth
        from tblearningpatterns
        where clientname=@client
            and earningpattern=@pattern
    )
    ,
    b as
    (
        select
            earningvalue,
            Mnth,
            earningvalue as Ttl
        from a
        where Mnth=@begin

        union all
        select
            a.earningvalue,
            a.Mnth,
            cast(b.Ttl*a.earningvalue as decimal(15,3)) as Ttl
        from a
            inner join b
                on a.Mnth=b.Mnth+1
        where a.Mnth<=@end

    )

    select @earningvalue=
        Ttl
    from b
        inner join
        (
            select max(Mnth) as Mnth
            from b
        ) c
            on b.Mnth=c.Mnth
    option(maxrecursion 12)


    SET @earnedpremium =  @earningvalue*@premium 

end

有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:1)

这是因为收益正在乘以递归CTE的收益。 b.Ttl * a.earningvalue

这个查询似乎是错误的......只是从它看来它会让你说你从一年到下一年。作为例子,月份从12变为1

我会创建一个递归CTE,它基本上使用你的开始日期锚定,然后在联合之后的部分中我将1 $ onth添加到Datetime直到它超过结束日期

相关问题