递归添加多行

时间:2018-02-10 11:29:49

标签: sql postgresql

我有一个名为river的表格,其中有三列:nameriverlength

name是河的名称,river是这条河连接的河流,length是河的长度

示例表可能如下所示:

name       | river      | length
           |            |  
Amazonas   |            | 3778
Rio negro  | Amazonas   | 2886
Huallaga   | Rio Negro  | 1138
Nile       |            | 3090
White Nile | Sobat      | 950
Sobat      | White Nile | 740

我想递归将我在这里完成的河流长度加在一起:

with recursive cte as(
select name, river,length from river
where name = 'Amazonas'
Union all
select r.name,r.river,r.length from river r
join cte s on r.river = s.name
)
select sum(length) from cte;

但是我也希望能够将不同的父河流加在一起,并按照这样的方式对它们进行分组:

name       combined_length
Amazonas | 7802
Nile     | 6203
Volga    | 6234

我尝试将or语句添加到上面的代码中,如下所示:

where name = 'Amazonas' or name = 'Nile' or name = 'Volga'

但是我不能用他们的父母对它们进行分组,我只能将每条河(亚马逊,尼罗河和伏尔加组合)的所有长度加在一起,或者如果我尝试使用group by,则根本不添加它们。

我还尝试用以下三种不同的子查询:

length from river
where name = 'Amazonas'
Union all
select r.name,r.river,r.length from river r
join cte s on r.river = s.name

并用我想要的河流替换名称,但后来我得到了错误:

recursive query "cte" does not have the form non-recursive-term UNION [ALL] recursive-term

1 个答案:

答案 0 :(得分:0)

我期待这样的事情来获得所有母河的长度:

with recursive cte as (
      select name, river, length, name as parent
      from river r
      where r.river is null
      union all
      select r.name, r.river, r.length, cte.parent
      from river r join
           cte s
           on r.river = s.name
     )
select parent, sum(length)
from cte
group by parent;