create table Total_Points ( id int primary key identity(1,1), Code int Unique, Points int ) --insert into Total_Points values(1001,10) --insert into Total_Points values(2001,20) --insert into Total_Points values(3001,30) --insert into Total_Points values(4001,40) --insert into Total_Points values(5001,50) --select * from Total_Points --select * from Points_TRN --create table Points_TRN --( --id int primary key identity(1,1), --RefCode int , --EarnPoints int --) --insert into Points_TRN values(1001,1) --insert into Points_TRN values(1001,2) --insert into Points_TRN values(1001,3) --insert into Points_TRN values(2001,2) --insert into Points_TRN values(2001,2) --insert into Points_TRN values(2001,2) --insert into Points_TRN values(3001,7) --insert into Points_TRN values(3001,5) --insert into Points_TRN values(3001,4) --Expected Output -- id Code Totalpoint Earnpoint FinalPoint 1 1001 10 6 4 2 2001 20 6 14 3 3001 30 16 14 4 4001 40 0 0 5 5001 50 0 0