首先我們需要聲明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()進行計算。 –