SQL DB2:要根据父ID查找已删除子项的计数吗

SQL DB2:要根据父ID查找已删除子项的计数吗,sql,count,db2,parent-child,Sql,Count,Db2,Parent Child,我有一个表格,你可以看到每种类型的实体的完整列表,以及哪个儿子是谁的父亲 人 ID | Deleted | Type | Father_id 1 | 0 | Father | null 2 | 0 | Son | 1 3 | 1 | Daughter | 1 4 | 1 | Son | 5 5 | 0 | Father |

我有一个表格,你可以看到每种类型的实体的完整列表,以及哪个儿子是谁的父亲

ID  | Deleted  |  Type      | Father_id
1   |     0    |   Father   |  null
2   |     0    |   Son      |    1
3   |     1    |   Daughter |    1 
4   |     1    |   Son      |    5
5   |     0    |   Father   |  null
6   |     0    |   Father   |  null
7   |     1    |   Son      |    5
8   |     0    |   Daughter |    5
9   |     0    |   Father   |  null
10  |     1    |   Son      |    6
11  |     0    |   Father   |  null
我想拉一下删除孩子的数量,以防父亲没有儿子,我也必须展示它

Father_id   | NumberOfDeletedSons
Father1     |         1
Father5     |         2
Father6     |         1
Father9     |        No Sons
Father11    |        No Sons
我做了一个查询来检查子记录的总数,但是我不知道如何提取被删除的子记录的数量

SELECT father, COUNT(*) AS numSons FROM PEOPLE where type in ('Daughter','Son') and deleted=0 GROUP BY father

提前感谢。

首先,创建一个
不同的
父亲表。然后将
外部联接
计数
一起使用,以获得总数:

select fathers.father_id, 
       count(children.id) NumberOfDeletedSons
from (select distinct id, type, concat(type,id) father_id
      from people
      where father_id is null) a fathers
   left join people as children on fathers.id = children.father_id
                                 and children.deleted = 0
group by fathers.father_id

这是具有聚合的自联接:

select f.id as father_id,
       (case when max(s.id) is null then 'No sons'
             else cast(sum(deleted) as varchar(255))
        end) as NumberOfDeletedSons
from people f left join
     people s
     on s.father_id = f.id and s.type = 'Son'
where f.type = 'Father'
group by f.id

检查@sgeddes答案确实对我有用,但有一点小小的调整:

SELECT FATHERS.FATHER_ID, 
       COUNT(CHILDREN.ID) NUMBEROFDELETEDSONS
FROM (SELECT DISTINCT ID, FATHER_ID
      FROM PEOPLE
      WHERE DELETED=0) AS FATHERS
   LEFT JOIN PEOPLE AS CHILDREN ON FATHERS.ID = CHILDREN.FATHER_ID
                                 AND CHILDREN.DELETED = 1
GROUP BY FATHERS.FATHER_ID