【问题标题】:How to find the parent and child relation in sql如何在sql中找到父子关系
【发布时间】:2020-12-21 18:36:59
【问题描述】:

我有如下数据,并试图获取父母所用时间的总和。

输入

ID_P    ID_C    SLA FL
1       2     0.2   Y
2       3     0.5   N
3       4     0.5   N
8       9     1.5   Y
9       10    0.1   N
10            0.2   N

预期输出

ID_P    Sum(SLA)
1       1.2
8       1.8

有人可以帮我处理 SQL。

【问题讨论】:

  • 您使用的是哪个 dbms?
  • SQL Server 数据库
  • 尝试递归 cte。

标签: sql sql-server common-table-expression hierarchical-data recursive-query


【解决方案1】:

您可以使用递归查询。这个想法是从父行开始 - 据我了解您的数据,这些行由列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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多