SELECT SUM(t.AdjustedBalance) AS Allqmye FROM ( SELECT * FROM ( SELECT ROW_NUMBER() OVER ( PARTITION BY change.AccountSysNo ORDER BY change.indate DESC ) AS RowNumber , (CASE WHEN account.Source=1 THEN account.VendorSysNo ELSE account.DistributorSysNo END ) AS SysNo, change.InDate, change.AccountSysNo, change.AdjustedBalance FROM [BBCFinance].[dbo].[AccountBalanceChange] change INNER JOIN BBCAccount.dbo.Account account ON account.SysNo = change.AccountSysNo LEFT JOIN BBCAccount.dbo.Vendor V WITH ( NOLOCK ) ON V.SysNo = Account.VendorSysNo LEFT JOIN BBCAccount.dbo.Distributor D WITH ( NOLOCK ) ON D.SysNo = Account.DistributorSysNo ) r WHERE SysNo=2272 AND InDate >= '2016/11/23 0:00:00' AND InDate <= '2016/11/30 0:00:00' ) t WHERE RowNumber=1 SELECT SUM(t.AdjustedBalance) FROM ( SELECT ROW_NUMBER() OVER ( PARTITION BY change.AccountSysNo ORDER BY change.indate DESC ) AS RowNumber , (CASE WHEN Account.Source=1 THEN Account.VendorSysNo ELSE Account.DistributorSysNo END ) AS SysNo, change.AccountSysNo, change.AdjustedBalance FROM [BBCFinance].[dbo].[AccountBalanceChange] change INNER JOIN BBCAccount.dbo.Account account ON account.SysNo = change.AccountSysNo LEFT JOIN BBCAccount.dbo.Vendor V WITH ( NOLOCK ) ON V.SysNo = Account.VendorSysNo LEFT JOIN BBCAccount.dbo.Distributor D WITH ( NOLOCK ) ON D.SysNo = Account.DistributorSysNo WHERE account.VendorSysNo = 2272 AND change.InDate >= '2016/11/23 0:00:00' AND change.InDate <= '2016/11/29 23:59:59' ) t WHERE t.RowNumber=1