2017-04-04 80 views
0

我有一個複雜的問題,需要在t-sql中解決。可能沒有遊標或循環。T-SQL業務規則計算

根據客戶的付款設置給出以下表格。

ID Frequency Amount Start Date End Date 
1 Monthly  100  01-01-2016 N/A(ongoing) 

客戶想知道他\她需要爲11月份付多少錢。 如果他們收在15月考慮2016年

例如:

假設客戶希望結束對11月15日-2016的帳戶,並想知道他們將$量從11月1日至11月15日支付。

計算

爲客戶支付的頻率週期爲每月一次。 以頻率進去,我們知道:

  • 月的客戶開始日期將是11月1日
  • 的結束日期將在11月

計算公式

所以我們可以告訴客戶他/她將在11月支付50美元,如果他們要關閉該帳戶於11月15日。

+0

你在哪裏得到結束日期?似乎如果您列出表格格式並使用參數傳遞日期,您可以輕鬆使用DATEDIFF()和EOMONTH()進行計算。 –

回答

0

首先我們需要聲明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] 
+0

如果select語句的返回值是所需的數字,爲什麼還需要第二個變量? –

+0

@amountDue是每月到期的金額。返回的價值是在選擇日期支付的到期金額。所以如果有人在這個月的一段時間內關閉了他們的賬戶,那麼他們在整個月中都沒有收到賬單。 但我看到了混亂。編輯更清晰。 –

+0

謝謝Andrew,還有一個問題。你可以請嘗試包括每兩週頻率計算以及? I.E有可能會每兩週而不是每月設置一次付款。 – John