Sql-server – Query Require for Opening and Closing

sql server 2014

I want to Calculate opening and Closing between two table.
Below is Data and expected output

 Create table #tbl_Receivable (Rec_ID int,Inv_ID int ,Customer_ID int,Rec_Date date,Rec_Amount varchar(50),Inv_type varchar(50),item_Weight int);
  Create table #tbl_Shop_InvM (Inv_ID int ,Customer_ID int,E_Date date,Rec_Amount varchar(50),Inv_type varchar(50),item_Weight int);
   Create table #tbl_Customer ( Customer_ID int ,Customer_Name varchar(50));

 insert into #tbl_Customer values (1,'Akhter'), (2,'Hussian');

INSERT INTO #tbl_Shop_InvM VALUES
(211,1,'2020-03-06',5000,'Payable',0), 
(222,1,'2020-03-08',8000,'Payable',0),
(223,2,'2020-03-08',2000,'Payable',0),
(224,1,'2020-03-09',5500,'Payable',0),
(225,2,'2020-03-10',15000,'Payable',500)



INSERT INTO #tbl_Receivable VALUES
   (112,211,1,'2020-03-07',2000,'Received',0),
(115,222,1,'2020-03-09',4000,'Received',0),
(116,222,1,'2020-03-09',2000,'Received',0),
(117,211,1,'2020-03-12',1000,'Received',0),
(118,225,2,'2020-03-11',15000,'Received',0);

I want Below ouput in which Date is giving from 06-03-2020 to 12-03-2020 ,then opending will be 0,because there is not invoice before 06-03-2020 ,
if Date is giving from 12-06-2020 to 12-06-2020 ,then opening will be 09-03-2020 balance 10500

Desire Output

enter image description here

Best Answer

First of all, your Rec_Amount columns should be changed from varchar to something numerical like float.

Secondly, i think you wrote the wrong range in this sentence so i don't understand what you mean here.

if Date is giving from 12-06-2020 to 12-06-2020 ,then opening will be 09-03-2020 balance 10500

I believe this query gives the desired output:

SELECT q.Customer_ID, q.E_Date, q.Payable, q.Received, q.Balance
FROM
(SELECT Customer_ID, E_Date, Payable, Received, SUM(CAST(ISNULL(Payable, 0) AS float)-CAST(ISNULL(Received, 0) AS float)) OVER(PARTITION BY Customer_ID ORDER BY E_Date) AS Balance
FROM
(SELECT s.Customer_ID, s.E_Date, s.Rec_Amount, s.Inv_type
FROM #tbl_Shop_InvM s 
UNION ALL 
SELECT r.Customer_ID, r.Rec_Date, r.Rec_Amount, r.Inv_type
FROM #tbl_Receivable r) AS a 
PIVOT
(MAX(Rec_Amount)
FOR Inv_type IN ([Payable],[Received])) AS p) AS q

/*Set date range */
--WHERE q.E_Date BETWEEN '2020-03-07' AND '2020-03-11'

Output:

enter image description here