Share via

Expected OutPut require

Analyst_SQL 3,576 Reputation points
2021-04-28T00:51:04.027+00:00

I need below output with data below.
Net Total is column total,then Pending is coming from table and Grand Total (Pending+Net Total)

Create table #tbl_Account_L_Four (Level_Four_ID int,Level_Four_Name varchar(50))  
CREATE TABLE #tbl_Invoice(ID INT,Level_Four_ID int,qty int,Rate int,Pending INT,Inv_date date);  
  
Insert into #tbl_Account_L_Four values  
(1001,'akhter'),  
(1002,'Ali')  
  
INSERT INTO #tbl_Invoice VALUES  
  (1,1001,2,10,0,'01-04-2021')  
, (2,1001,15,2,25,'01-04-2021')  
, (3,1002,40,120,0,'01-04-2021')  

91865-image.png

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories


Answer accepted by question author

EchoLiu-MSFT 14,626 Reputation points
2021-04-28T03:35:27.903+00:00

Please refer to:

;WITH cte  
 as(SELECT Level_Four_Name AS Customer,'Water' AS [Description]  
 ,ti.Qty,ti.Rate,ti.Pending,Total=ti.QTY * ti.Rate  
 FROM #tbl_Account_L_Four ta  
 JOIN #tbl_Invoice ti  
 ON ta.Level_Four_ID=ti.Level_Four_ID   
 WHERE ta.Level_Four_ID=1001)  
  
 SELECT Customer,[Description],CAST(Qty as varchar)Qty,CAST(Rate as varchar) Rate,Total   
 FROM cte  
 UNION ALL   
 SELECT '','','','Net Total',Sum(Total) FROM cte  
 UNION ALL   
 SELECT '','','','Pending',(SELECT Pending FROM cte WHERE Pending<>0)  
 UNION ALL   
 SELECT '','','','Grand Total', Sum(Total)+(SELECT Pending FROM cte WHERE Pending<>0) FROM cte  
  

Output:
91818-image.png

Regards
Echo


If the answer is helpful, please click "Accept Answer" and upvote it.

Was this answer helpful?

1 person found this answer helpful.
0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.