Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Select Master Records and Display Number of Detail Records for Each

I have a Master and Detail table, the Detail linking to the Master record on a FK reference.

I need to display all the data from the Master table, and the corresponding number of details for each record, i.e.

MASTER TABLE
ID Name  Age
1  John  15
2  Jane  14 
3  Joe   15

DETAIL
MasterID Subjects
1        Trigonometry
1        Chemistry
1        Physics
1        History
2        Trigonometry
2        Physics

Thus, when I ran the SQL statement, I would have the following result:

ID Name Age #Subjects
1  John 15  4  
2  Jane 14  2
3  Joe  15  0

Thanks!

like image 646
Batuta Avatar asked Oct 21 '10 19:10

Batuta


People also ask

How display total number of records in SQL?

The SQL COUNT(), AVG() and SUM() Functions The COUNT() function returns the number of rows that matches a specified criterion.

Which SQL function is used to count the number of records?

The SQL COUNT( ) function is used to return the number of rows in a table. It is used with the Select( ) statement.

Can you list the ways to get the count of records in a table?

With the help of the SQL count statement, you can get the number of records stored in a table.


1 Answers

This may be useful

SELECT mt.ID, mt.NAME, mt.AGE, COUNT(d.MasterID) as [#Subjects]
FROM MasterTable mt
LEFT OUTER JOIN Detail d on mt.ID = d.ID
GROUP BY mt.ID, mt.NAME, mt.AGE
ORDER BY mt.ID
like image 85
bobs Avatar answered Nov 15 '22 08:11

bobs