0

Table 1:

ID (unqiue), Name, Address

Table 2:

RecordId, ID (key of table 1),  Child name

In one query, I want to retrieve all rows of Table 1 with one additional column which will be the count of all record in table 2 from ID (that is number of children for each ID in table 1). Can't figure out how to format a query to retrieve this data.

1
  • I think JOIN query should give you an idea regarding this problem. Commented Jan 19, 2017 at 4:39

3 Answers 3

2

Simply Join and apply count

select T1.*, COUNT(T2.RECORDID)AS T2COUNT from Table1 T1
INNER JOIN TABLE2 T2 ON T1.ID= T2.ID
--LEFT JOIN  TABLE2 T2 ON T1.ID= T2.ID  --if you need 0 child records (from commets by @Cha)
GROUP BY T1.ID  , T1.Name, T1.Address
Sign up to request clarification or add additional context in comments.

2 Comments

And what if someone has no children?
Hmm.. need Left join though. @cha
1

The correct way of doing this will be with a OUTER JOIN:

SELECT a.ID, a.Name, a.Address, b.cnt
FROM Table1 a
LEFT OUTER JOIN
(SELECT ID, count(*) cnt from Table2 GROUP BY ID) b
ON a.ID = b.ID

The incorrect way will be with a help of a correlated sub-query:

SELECT a.ID, a.Name, a.Address, 
(SELECT count(*) FROM Table2 b WHERE b.ID = a.ID) as cnt
FROM Table1 a

Here is a discussion about correlated subqueries vs OUTER JOINs, if you are interested

6 Comments

And why Left Join a Set?
@ShakeerMirza: to select people without children?
@ShakeerMirza: I feel that grouping by ID, Name, Address like you did works in this particular case until you start adding more tables. You add another table to your query and suddenly realise that you need to add more columns to the GROUP BY clause. In my opinion it is excessive
Yeah came to know the intention of Sub set. Upvoted for the same already.
Also, if you need to add more columns to the T1 (like email, address, phone etc) they need to be repeated in the SELECT clause and in the GROUP BY clause
|
0

Group by table1 fields and count total records in table2: here T1 alias of table1 and T2 alias of table2.

select T1.ID, T1.Name, T1.Address, count(T2.ID) as total_records
from table1 as T1
left outer join table2 as T2 on T2.ID=T1.ID
group by T1.ID, T1.Name, T1.Address

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.