简体   繁体   English

SQL Server交易利息计算

[英]SQL Server Interest calculations on transactions

I'm looking for advice on best way to build a compound interest module in SQL server. 我正在寻找有关在SQL Server中构建复利模块的最佳方法的建议。 Basic set up: Table: Transactions {TransID, MemberID, Trans_Date, Trans_Code, Trans_Value). 基本设置:表:事务{TransID,MemberID,Trans_Date,Trans_Code,Trans_Value)。 Table: Interest {IntID, Int_eff_Date, Int_Rate} 表格:利息{IntID,Int_eff_Date,Int_Rate}

In the interest table, there may be different rates with an effective date - can never have an over lapping date though. 在利息表中,生效日期可能有不同的利率-但是永远不能有重叠日期。 For example: 例如:

Int_Eff_Date       Int_Rate
01/01/2016         7%
01/10/2016         7.5%
10/01/2017         8%

I want to calculate the interest based on the transaction date and transaction value, where the correct interest rate is applied relative to transaction date. 我想基于交易日期和交易价值计算利息,其中相对于交易日期应用了正确的利率。

So if Table transaction had: 因此,如果表事务具有:

TransID   MemberID    Trans_Date    Trans_Value
1         1            15/04/2016    150
2         1            18/10/2016    200
3         1            24/11/2016    200
4         1            15/01/2017    250

For transID 1 it would use 7% from 15/04/2016 until 30/09/2016 (168 days) from 1/10/2016 to 09/01/2017 it would use 7.% and then from 10/01/2007 to calculation date (input parameter) it would use 8%. 对于transID 1,它将使用7%,从15/04/2016到30/09/2016(168天),从1/10/2016到09/01/2017,它将使用7.%,然后从10/01/2007到计算日期(输入参数),将使用8%。

It would apply similar methodology for all transactions, add them up and display the interest value. 它将对所有交易采用类似的方法,将其加总并显示利息价值。

I'm not sure if I should use cursors, UDF, etc. 我不确定是否应该使用游标,UDF等。

This should provide an outline of what you're trying to do. 这应该提供您要做什么的概述。

--Build Test Data
CREATE TABLE #Rates(Int_Eff_Date DATE
                    , Int_Rate FLOAT)
CREATE TABLE #Transactions(TransID INT
                            ,MemberID INT
                            ,Trans_Date DATE
                            ,Trans_Value INT)

INSERT INTO #Rates     
VALUES  ('20160101',7)
        ,('20161001',7.5)
        ,('20170110',8)

INSERT INTO #Transactions
VALUES 
(1,1,'20160415',150)
,(2,1,'20161018',200)
,(3,1,'20161124',200)
,(4,1,'20170115',250)


;WITH cte_Date_Rates
    AS
    (
    SELECT 
        S.Int_Eff_Date
        ,ISNULL(E.Int_Eff_Date,'20490101') AS "Expire"
        ,S.Int_Rate
    FROM
        #Rates S 
            OUTER APPLY (SELECT TOP 1 Int_Eff_Date 
                        FROM #Rates E 
                        WHERE E.Int_Eff_Date > S.Int_Eff_Date
                        ORDER BY E.Int_Eff_Date) E 
    )
SELECT
    T.*
    ,R.Int_Rate
FROM
    #Transactions T 
        LEFT JOIN cte_Date_Rates R
            ON
            T.Trans_Date >= R.Int_Eff_Date
            AND
            T.Trans_Date < R.Expire

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM