Click here to Skip to main content
15,905,915 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have following tables with data as given below

Batch-Information
-----------------
Batch-code	total-seats	
----------      -----------
b1		30
b2		25
b3		35
b4		40




Admission-Information
---------------------
Admno	Sname	Batch-code
-----   -----   ----------
1	a	b1
2	b	b3
3	c	b3
4	d	b3
5	e	b1
6	f	b4
7	g	b2
8	h	b4
9	i	b1
10	j	b2


I want to write a query to show the output as follows

C#
Batch-code	total-seats	Filled-Seats	Vacant-seats
----------      -----------     ------------    ------------
b1		30		3		27
b2		25		2		23
b3		35		3		32
b4		40		2		38




But I did not get how to count total seats filled seats vacant seats etc in query.
Thanks in advance for help

What I have tried:

C#
SELECT * FROM Admission-Information AA LEFT OUTER JOIN Batch-Information e2
ON AA.Batch-Code = BB.Batch-Code


Also tried count(*) But not successful
Posted
Updated 18-Jan-18 22:25pm
v2

Probably, you need to add a GROUP BY:
SQL
SELECT [Batch-Code], COUNT(*) AS Filled FROM [Admission-Information]
GROUP BY [Batch-code]
Will give you the "filled seats" you need, so then all you have to do is JOIN that:
SQL
SELECT b.[Batch-code] , b.[Total-Seats], fs.Filled, b.[Total-Seats] - fs.Filled AS [Vacant-seats]
FROM [Batch-Information] b
JOIN (SELECT [Batch-Code], COUNT(*) AS Filled FROM [Admission-Information]
      GROUP BY [Batch-code]) fs 
ON b.[Batch-code] = fs.[Batch-code]
Which will give you what you wanted.
 
Share this answer
 
v2
Comments
CodeMine 19-Jan-18 9:34am    
thanks this solved my problem. thanks great
SELECT Batchcode,
	totalseats,
	isnull((
			SELECT COUNT(1)
			FROM @AdmissionInformation a
			WHERE a.Batchcode = b.Batchcode
			GROUP BY Batchcode
			), 0) AS FilledSeats,
	totalseats - isnull((
			SELECT COUNT(1)
			FROM @AdmissionInformation a
			WHERE a.Batchcode = b.Batchcode
			GROUP BY Batchcode
			), 0) AS Vacantseats
FROM @BatchInformation b
 
Share this answer
 

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