最初に、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()を簡単に使用できる日付で渡すパラメータを使用しているようです。 –