Hi @Analyst_SQL ,
Please refer below updated query:
declare @begin_date date = '2020-03-06';
declare @end_date date = '2020-03-11';
;with cte as (
select Customer_id ,'' Descript,E_Date,Convert(VARCHAR(50),rec_amount) Payable,'' received
from #tbl_Shop_InvM
where #tbl_Shop_InvM.Customer_ID=1 and Inv_Type='Payable' --and (E_date between @begin_date and @end_date)
union
select Customer_id ,'' Descript,rec_date E_Date,'' Payable,Convert(VARCHAR(50),rec_amount) received
from #tbl_Receivable
where #tbl_Receivable.Customer_ID=1 and Inv_Type='Received'-- and (Rec_Date between @begin_date and @end_date)
),cte1 as (
select *,Payable+ received*-1 balance from cte
union all
select distinct a.Customer_id,'Openning' Descript, dateadd(day,-1,@begin_date) E_Date,0 Payable,0 Received, b.opening Balance
from cte a
inner join #tbl_Customer b on a.Customer_ID=b.Customer_ID
),
cte2 as (
select Customer_id,Descript,E_Date,Payable,Received,
sum(balance) OVER (PARTITION BY Customer_id ORDER BY e_date ROWS UNBOUNDED PRECEDING) Balance
from cte1)
,cte3 as
(select Customer_id,'Openning' Descript, E_Date,0 Payable,0 Received, Balance
,ROW_NUMBER() OVER(PARTITION BY Customer_id ORDER BY (select null)) rn
from cte2
where E_Date < @begin_date)
select Customer_id,Descript,dateadd(day,-1,@begin_date) E_Date,Payable,Received,Balance from cte3 where rn=(select max(rn) from cte3)
union all
select * from cte2 where E_Date between @begin_date and @end_date
order by E_Date
Best regards
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Hot issues November--What can I do if my transaction log is full?
Hot issues November--How to convert Profiler trace into a SQL Server table