如何在sql中查找父关系和子关系
我有下面这样的数据,并试图得到家长所花时间的总和 输入 预期产量如何在sql中查找父关系和子关系,sql,sql-server,common-table-expression,hierarchical-data,recursive-query,Sql,Sql Server,Common Table Expression,Hierarchical Data,Recursive Query,我有下面这样的数据,并试图得到家长所花时间的总和 输入 预期产量 ID_P Sum(SLA) 1 1.2 8 1.8 有人能帮我使用SQL吗。您可以使用递归查询。我们的想法是从父行开始,据我所知,父行由列fl标识。然后你可以按照链接到孩子们。最后一步是聚合: with cte as ( select idp_p, id_c, sla from mytable where fl = 'Y' union all select c.id_p, t
ID_P Sum(SLA)
1 1.2
8 1.8
有人能帮我使用SQL吗。您可以使用递归查询。我们的想法是从父行开始,据我所知,父行由列
fl
标识。然后你可以按照链接到孩子们。最后一步是聚合:
with cte as (
select idp_p, id_c, sla from mytable where fl = 'Y'
union all
select c.id_p, t.id_c, t.sla
from cte c
inner join mytable t on t.id_p = c.id_c
)
select id_p, sum(sla) as sum_sla from cte group by id_p
您正在使用哪个dbms?SQL Server数据库尝试递归cte。
with cte as (
select idp_p, id_c, sla from mytable where fl = 'Y'
union all
select c.id_p, t.id_c, t.sla
from cte c
inner join mytable t on t.id_p = c.id_c
)
select id_p, sum(sla) as sum_sla from cte group by id_p