首先我们需要声明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]
你在哪里得到结束日期?似乎如果您列出表格格式并使用参数传递日期,您可以轻松使用DATEDIFF()和EOMONTH()进行计算。 –