2017-06-12 52 views
0

我有一個查詢,我用它來產生的報表顯示的月份是根據日期參數計算的金額到期日@StartDate和@EndDate如何在SQL Server 2014中獲得@StartDate - 30?

包括在聲明中,我想添加到期金額上個月(上個月的餘額欠款)日期範圍@StartDate - 30到@EndDate - 30.運行該代碼的代碼是什麼?

我的代碼:

set nocount on 

Declare @S AS DateTime = ISNULL(@StartDate,DateAdd(d,-60,GETDATE())) 
Declare @anum as nvarchar(8) = ISNULL(@panum,'25991275') 
Declare @E AS DateTime = ISNULL(@EndDate,DateAdd(d,-0,GETDATE())) 

SELECT A.AccountNumber 
     ,C.FirstName + ' ' + C.LastName CustName 
     ,[InvoiceNumber] 
     ,[StatementDate] 
     ,[NewCharges] 
     ,[AmountDue] 
     ,[Charges] 
     ,[AccountFee] 
     ,[Interest] 
     ,[Payments] 
     ,[Refunds] 
     ,[DueDate] 


FROM [StatementSummary] S 
INNER JOIN Account A ON S.AccountID = A.Accountid 
INNER JOIN Contact C ON A.AccountId = C.AccountId 


WHERE A.AccountNumber = @anum 
    AND StatementDate >= @S 
    AND StatementDate <= @E 

ORDER BY StatementDate DESC 

我想製作另一個數據集的運行下面的代碼:

SELECT Top 1 AcctBalance  
    FROM [FinMaster] 
    WHERE AcctID = @anum 
    AND BusinessDay >= @S - 30 
    AND BusinessDay <= @E - 30 

    ORDER BY AcctBalance DESC 

如何添加日期範圍,返回前一個一個月?

如果我可以將第二個代碼添加爲第一個代碼中的一行,那麼我將不需要爲我的報告創建第二個數據集。

+0

謝謝。我將如何把它放在代碼中? – user1777929

+0

實際上應該是OUTER應用和Eomonth功能 – maSTAShuFu

回答

0

使用OUTER APPLY和EOMONTH函數來獲取上個月值
只是一個邏輯,而不是使用領域

declare @reportdate date = getdate() 

select a.*, x.field.... 
from table1 A 
    OUTER apply (  --- to get last month data, can be null.. similar to left outer join but in a cartesian way of display 
    select b.field1, b.field2, b.... 
    from table1 B 
    where 
    b.product_id = a.product_id and 
    trans_date 
    between -- between last month based on the @reportdate 
    dateadd(day,1,eomonth(dateadd(month,-2,@reportdate))) -- or  a.trans_date 
    and 
    eomonth(dateadd(month,-1,@reportdate)) 
    ) x 
where trans_date 
    between -- your reporting date, can be any date 
    dateadd(day,1,eomonth(dateadd(month,-1,@reportdate))) 
    and eomonth(@reportdate)