2017-06-12 51 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)