SQL COUNT & GROUP BY

2020-05-10 11:56发布

I have this table

---ID----NAME----INVITED_BY---
   1      A         
   2      B          1
   3      C          1
   4      D          2

all I want is to get the result:

---ID----NAME------INVITES---------
   1      A          2 (COUNT OF INVITED_BY)
   2      B          1
   3      C          0
   4      D          0

标签: mysql sql
1条回答
家丑人穷心不美
2楼-- · 2020-05-10 12:31

You could do a self join to count the number of persons invited:

select  yt.id
,       yt.name
,       count(distinct inv_by.id) as invites
from    YourTable yt
left join    
        YourTable inv_by
on      yt.id = inv_by.invited_by
group by
        yt.id
,       yt.name
查看更多
登录 后发表回答