DECLARE @BeginDate Datetime DECLARE @EndDate Datetime Set @BeginDate = '06-01-2015' Set @EndDate = '06-30-2015' DECLARE @tblData table ( RECORDTYPE varchar(25), AgentName varchar(100), Balance_before numeric(10,2), EscrowAmountApplied numeric(10,2), TotalEscrowAmountApplied numeric(10,2), Balance_After numeric(10,2), TransactionDate datetime, Address1 varchar(50), Address2 varchar(50), City varchar(50), State varchar(50), Zip varchar(50) ) SELECT A.*, B.Balance_After FROM (SELECT t1.RECORDTYPE, T1.AgentName, T1.Balance_before, t1.EscrowAmountApplied, t1.TotalEscrowAmountApplied, t1.Address1, t1.Address2, t1.City, t1.State, t1.Zip FROM @tblData T1 INNER JOIN -- Take the Beginning Escrow Balance for an agent (Escrow Balance Before) within the date range for an agent (SELECT AgentName, TotalEscrowAmountApplied, MIN( TransactionDate) minDT from @tblData GROUP BY AgentName, TotalEscrowAmountApplied) T2 ON T1.AgentName = T2.AgentName AND T1.TotalEscrowAmountApplied = T2.TotalEscrowAmountApplied AND T1.TransactionDate = T2.minDT ) A INNER JOIN -- Take the Ending Escrow Balance for an agent (Escrow Balance After) within the date range for an agent (SELECT t1.RECORDTYPE, T1.AgentName, T1.Balance_After FROM @tblData T1 INNER JOIN (SELECT AgentName, MAX( TransactionDate) maxDT from @tblData GROUP BY AgentName) T2 ON T1.AgentName = T2.AgentName AND T1.TransactionDate = T2.maxDT ) B ON A.AgentName = B.AgentName
I have the following result with the help from our forum experts here.
I need modify the query to produce the following result set:
Attached is my current SQL query:
Thank you all for your help.