A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
Hi @Analyst_SQL ,
Please try:
;with cte as
(select tb.B_ID,sum(isnull(tg.G_Qty,0)) G_Qty
from #tbl_bottles tb
left join #tbl_GRN tg on tb.B_ID=tg.B_ID
group by tb.B_ID)
,cte2 as
(select tb.B_ID,sum(isnull(ti.I_Qty,0)) I_Qty
from #tbl_bottles tb
left join #tbl_Issue ti on tb.B_ID=ti.B_ID
group by tb.B_ID)
,cte3 as
(select t.B_Name Item,c.G_Qty,c2.I_Qty,isnull((c.G_Qty-c2.I_Qty),0) balance
from cte c
join cte2 c2 on c.B_ID=c2.B_ID
join #tbl_bottles t on c.B_ID=t.B_ID)
select * from cte3
union all
select 'Total', sum(G_Qty),sum(I_Qty),sum(balance)
from cte3
Output:
Item G_Qty I_Qty balance
19Liter 13 7 6
6Liter 0 0 0
2Liter 12 8 4
Nozzel 0 0 0
Cap 6 0 6
Stand 0 0 0
Pump 0 0 0
Pip 0 0 0
Blue Stand 0 0 0
Total 31 15 16
Regards
Echo
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.