Click here to Skip to main content
15,893,190 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am having two tables

table 1 with sal details

ID ENAME SAL
1 ANU 10000
2 APARNA 20000
3 ANANYA 15000
4 ANUPAMA 40000
5 AMRUTHA 20000

table 2 with advance details

ID ADVANCE
1 1000
2 500
5 200
1 2000
2 200

What I have tried:

i want to subtract the value of advance in table2 from sal in table

output:>

ID ENAME remainin_SAL

1 ANU 7000
2 APARNA 19300
3 ANANYA 15000
4 ANUPAMA 40000
5 AMRUTHA 19800
Posted
Updated 6-Aug-18 3:04am
v2

1 solution

I hope I'm not doing your homework for you...

There are 2 things that make this a little tricky, first you have to construct an interim query that sums the advances and join to the main table. The second tricky thing is that you have to make sure all names are represented in the interim query so they will not be excluded by the join. This means accounting for NULLS and replacing with a ZERO advance value.

drop table #tempadvance

CREATE TABLE #tempSaldetail(
	[ID] [int] NOT NULL,
	[ENAME] [varchar](32) NOT NULL,
	[SAL] [INT] NOT NULL
) 

CREATE TABLE #tempAdvance(
	[ID] [int] NOT NULL,
	[ADVANCE] [int] NOT NULL
	)
GO

insert into #tempSaldetail select 1, 'ANU', 10000
insert into #tempSaldetail select 2, 'APARNA', 20000
insert into #tempSaldetail select 3, 'ANANYA', 15000
insert into #tempSaldetail select 4, 'ANUPAMA', 40000
insert into #tempSaldetail select 5, 'AMRUTHA', 20000

INSERT INTO #tempAdvance SELECT 1, 1000
INSERT INTO #tempAdvance SELECT 2, 500
INSERT INTO #tempAdvance SELECT 5, 200
INSERT INTO #tempAdvance SELECT 1, 2000
INSERT INTO #tempAdvance SELECT 2, 200


SELECT s.ID, ENAME, s.Sal - (adv.totalAdvance) from #tempSaldetail s
join (select sal.id, ISNULL(sum(advance),0) as totaladvance from  #tempSaldetail sal  
	left outer join #tempAdvance A on 
	sal.id = a.id group by sal.id) as adv
on adv.id = s.id
 
Share this answer
 
Comments
Naga Sindhura 8-Aug-18 1:59am    
left outer gives poor performance when you have the bulk data. try this
SELECT TS.ID, TS.ENAME, TS.SAL - SUM(ISNULL(TA.ADVANCE,0)) 'remainin_SAL'
FROM #tempSaldetail TS
LEFT JOIN #tempAdvance TA On TA.Id = TS.id
group by TS.ID, TS.ENAME, TS.SAL
ORDER by TS.ID

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900