Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Count() child Rows based on values from Parent

Tags:

sql

mysql

db2

I have a Parent Table

EventKey   Event Name
1001       Event 1
1002       Event 2
1003       Event 3

This is my child Table

EventKey   EventAssignee
1001       Assignee 11
1001       Assignee 12
1002       Assignee 21
1002       Assignee 22

The below is my SQL Query

select p.EventKey As Event_Key,
       p.Event_Name As EventName,
       (select count(*) 
        from Child c 
        where c.eventkey = p.eventkey) As Assignee_Count
from ParentTable p

This is giving me a SQL Error unexpected token Child. Please let me know where am going wrong

Am Expecting the output to be

Event_Key Event_Name Assignee_Count
1001      Event 1    2    
1002      Event 2    2
1003      Event 3    0
like image 715
Hero Avatar asked Nov 25 '25 02:11

Hero


1 Answers

Try as this:

select p.EventKey As EventKey , p.EventName As EventName, count(c.assignee) As Assignee_Count
from Parent p left join child c on p.EventKey=c.EventKey 
group by p.EventKey,p.EventName 
like image 100
Gayathri Avatar answered Nov 26 '25 18:11

Gayathri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!