2017-04-04 78 views
0

我有一个复杂的问题,需要在t-sql中解决。可能没有游标或循环。T-SQL业务规则计算

根据客户的付款设置给出以下表格。

ID Frequency Amount Start Date End Date 
1 Monthly  100  01-01-2016 N/A(ongoing) 

客户想知道他\她需要为11月份付多少钱。 如果他们收在15月考虑2016年

例如:

假设客户希望结束对11月15日-2016的帐户,并想知道他们将$量从11月1日至11月15日支付。

计算

为客户支付的频率周期为每月一次。 以频率进去,我们知道:

  • 月的客户开始日期将是11月1日
  • 的结束日期将在11月

计算公式

所以我们可以告诉客户他/她将在11月支付50美元,如果他们要关闭该帐户于11月15日。

+0

你在哪里得到结束日期?似乎如果您列出表格格式并使用参数传递日期,您可以轻松使用DATEDIFF()和EOMONTH()进行计算。 –

回答

0

首先我们需要声明2个变量,有问题的日期和应付的每月金额。

DECLARE @date datetime = '2017-11-15' 
DECLARE @amountDue int = 100 

然后拿到当月到期日量,我们可以使用:

SELECT CAST(DATEPART(DAY,@date) AS FLOAT)/DATEPART(DAY,DATEADD(MONTH,DATEDIFF(MONTH,0,@date)+1,0)-1) * @amountDue AS [MonthToDateAmountDue] 

这里是我们如何到达那里。

SELECT 
    --This gets the first day of the next month and subtracts 1 day, getting the last day of the month the date falls in. 
    DATEADD(MONTH,DATEDIFF(MONTH,0,@date)+1,0)-1 AS [LastDayOfMonth] 
    --We now extract the day date part of the last day of the month to get the total days in the month. 
    ,DATEPART(DAY,DATEADD(MONTH,DATEDIFF(MONTH,0,@date)+1,0)-1) AS [DaysInMonth] 
    --Finally, we get the day date part from our @date and divide by the total days of the month to get the percentage of the month we have completed. 
    --Since int does not do decimals, we use a float. 
    ,CAST(DATEPART(DAY,@date) AS FLOAT)/DATEPART(DAY,DATEADD(MONTH,DATEDIFF(MONTH,0,@date)+1,0)-1) AS [PercentageOfMonthCompleted] 
    --And mulitply it by the amount due. 
    ,CAST(DATEPART(DAY,@date) AS FLOAT)/DATEPART(DAY,DATEADD(MONTH,DATEDIFF(MONTH,0,@date)+1,0)-1) * @amountDue AS [MonthToDateAmountDue] 

编辑:所以,我刚刚了解了EOMONTH函数。这可以缩短为

SELECT CAST(DATEPART(DAY,@date) AS FLOAT)/DATEPART(DAY,EOMONTH(@date)) * @amountDue AS AS [MonthToDateAmountDue] 
+0

如果select语句的返回值是所需的数字,为什么还需要第二个变量? –

+0

@amountDue是每月到期的金额。返回的价值是在选择日期支付的到期金额。所以如果有人在这个月的一段时间内关闭了他们的账户,那么他们在整个月中都没有收到账单。 但我看到了混乱。编辑更清晰。 –

+0

谢谢Andrew,还有一个问题。你可以请尝试包括每两周频率计算以及? I.E有可能会每两周而不是每月设置一次付款。 – John