我有一个复杂的问题,需要用t来解决.可能没有游标或循环。
给出了下表与客户的付款设置。
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。
计算
客户付款的频率周期是每月。考虑到频率,我们知道:
计算公式
(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美元。
发布于 2017-04-04 23:10:40
首先,我们需要声明这两个变量,日期和每月应付金额。
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]https://stackoverflow.com/questions/43218995
复制相似问题