首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >T-Sql业务规则计算

T-Sql业务规则计算
EN

Stack Overflow用户
提问于 2017-04-04 22:49:11
回答 1查看 45关注 0票数 0

我有一个复杂的问题,需要用t来解决.可能没有游标或循环。

给出了下表与客户的付款设置。

代码语言:javascript
运行
复制
ID  Frequency   Amount  Start Date  End Date
1   Monthly     100     01-01-2016  N/A(ongoing)

顾客想知道他在十一月份要付多少钱。如果他们在2016年11月15日关闭账户的话。

例如,

假设客户想要在2016年11月15日关闭他们的帐户,并想知道他们将在11月1日至11月15日期间支付的$amount。

计算

客户付款的频率周期是每月。考虑到频率,我们知道:

  • 客户的开始日期是11月1日。
  • 截止日期为11月30日。

计算公式

代码语言:javascript
运行
复制
(DayUpToCloseDate/DaysInNov) * Amount = amount customer is asking.

DaysUpToCloseDate = 15 (diff 1st of nov and 15th of nov)
DaysInNov = 30
Amount = 100
(15/30)*100 = 50

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-04 23:10:40

首先,我们需要声明这两个变量,日期和每月应付金额。

代码语言:javascript
运行
复制
DECLARE @date datetime = '2017-11-15'
DECLARE @amountDue int = 100

然后,为了获得每月到期的金额,我们可以使用:

代码语言:javascript
运行
复制
SELECT CAST(DATEPART(DAY,@date) AS FLOAT)/DATEPART(DAY,DATEADD(MONTH,DATEDIFF(MONTH,0,@date)+1,0)-1) * @amountDue AS [MonthToDateAmountDue]

我们是怎么到那里的。

代码语言:javascript
运行
复制
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函数。这可以缩短为

代码语言:javascript
运行
复制
SELECT CAST(DATEPART(DAY,@date) AS FLOAT)/DATEPART(DAY,EOMONTH(@date)) * @amountDue AS AS [MonthToDateAmountDue]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43218995

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档