【问题标题】:How to make SQL query with grouping in each node of an hierarchy tree?如何在层次树的每个节点中进行分组的 SQL 查询?
【发布时间】:2021-09-19 14:18:26
【问题描述】:

有一个表具有通常的“子到父”结构,其中每个节点都有权重。

TREE_TABLE
----------------------------------------
   id  | parent_id  |  name    | weight
----------------------------------------
   1   |  NULL      |   N1     |   51
   2   |  1         |   N12    |   62
   3   |  1         |   N13    |   73
   4   |  2         |   N124   |   84
   5   |  2         |   N125   |   95

// for convenience the "name" column shows path from a node to the root node

如何构建产生一组行的 SQL 查询,其中每行代表每个特定节点及其子节点的分组?

请根据您的选择使用任何 SQL 方言。只需要一个总体思路或解决方案的原型。

为了解决这个问题,我正在尝试使用 GROUPING SETS 和 ROLLUP 报告,但无法弄清楚如何处理“动态”分组级别数。

预期查询结果示例:

RESULT
--------------------------
 name  |  summary_weight
--------------------------
  N1   |   (51+62+73+84+95)
  N12  |   (62+84+95)    
  N124 |   (84)
  N125 |   (95)
  N13  |   (73)

【问题讨论】:

  • 为什么 N13 包含 51 (N1) 而 N12 不包含?
  • @JoachimIsaksson 这肯定是一个错字。当然,N13 只是 (73),因为它不包括父权重。谢谢。
  • 您希望值是 SUM 还是 (51+62+73+84+95) = 365TEXT (51+62+73+84+95)
  • @RuiCosta 实际上没有区别,因为通常它可以是任何聚合函数标准(sum,min,max)或自定义。为简单起见,我们假设“summary_weight”是值的总和(如示例中的 365)。
  • 添加了一个对两者都有帮助的答案:)

标签: sql oracle grouping-sets


【解决方案1】:

例如:

with 
 datum(id,parent_id,name,weight)
 as
 (
 select 1,NULL,'N1',51 from dual union all
 select 2 ,  1 , 'N12' , 62  from dual union all
 select 3 ,  1 , 'N13' , 73 from dual union all
 select 4 ,  2 , 'N124' , 84 from dual union all
 select 5 ,  2 , 'N125' , 95 from dual
 ),
 step1 as
 (
 select id,parent_id,name,weight, connect_by_root name  root,connect_by_isleaf is_parent 
 from datum
 connect by prior id = parent_id 
 )
select root,sum(weight)  sum_w,
 '('||listagg(weight,'+') within group(order by null) ||')' str_w,
 '('||listagg(name,'+') within group(order by null) ||')' str_n
from step1
group by root
order by 1;

链接:Hierarchical Queries

【讨论】:

  • 简直是天才。这是“START WITH”多余的罕见情况))
【解决方案2】:

如果你想SUM up,你可以使用这个选项:

SELECT 
  name, 
  (SELECT 
     sum(t2.weight) 
   FROM tree t2 
   WHERE t2.name LIKE t1.name || '%' )
FROM tree t1
ORDER BY rpad(name,10,'0');

如果你想连接文本,你可以使用这个:

SELECT 
  name, 
  (SELECT 
    '(' || string_agg(t2.weight || '','+') || ')' 
   FROM tree t2 
   WHERE t2.name LIKE t1.name || '%' )
FROM tree t1
ORDER BY rpad(name,10,'0');

【讨论】:

    猜你喜欢
    • 2010-09-17
    • 2014-12-23
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    相关资源
    最近更新 更多