Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
链表:查询存储在SQL表中的链表的第一个和最后一个元素_Sql_Postgresql_Linked List_Singly Linked List_Recursive Cte - Fatal编程技术网

链表:查询存储在SQL表中的链表的第一个和最后一个元素

链表:查询存储在SQL表中的链表的第一个和最后一个元素,sql,postgresql,linked-list,singly-linked-list,recursive-cte,Sql,Postgresql,Linked List,Singly Linked List,Recursive Cte,我有一个SQL表,其中的“行”表示链表的元素。 例如,我可以拥有以下记录: (id, previous_id) ------------------ (1, NULL) (2, NULL) (3, 2) (4, 3) (5, NULL) (6, 4) (7, 5) 本表中有3个列表: (1,) (2,3,4,6) (5,7) 我想找到每个列表的最后一个元素以及列表中的元素数。 我正在查找的查询将输出: last, len 1, 1 6, 4 7, 2 这在SQL中可能吗?您可以使用递归CT

我有一个SQL表,其中的“行”表示链表的元素。 例如,我可以拥有以下记录:

(id, previous_id)
------------------
(1, NULL)
(2, NULL)
(3, 2)
(4, 3)
(5, NULL)
(6, 4)
(7, 5)
本表中有3个列表:

(1,)
(2,3,4,6)
(5,7)
我想找到每个列表的最后一个元素以及列表中的元素数。 我正在查找的查询将输出:

last, len
1, 1
6, 4
7, 2

这在SQL中可能吗?

您可以使用递归CTE:

with recursive cte as (
      select l.previous_id as id, id as last
      from lines l
      where not exists (select 1 from lines l2 where l2.previous_id = l.id)
      union all
      select l.previous_id, cte.last
      from cte join
           lines l
           on cte.id = l.id
     )
select cte.last, count(*)
from cte
group by cte.last;

是一个dbfiddle。

您可以使用递归CTE:

with recursive cte as (
      select l.previous_id as id, id as last
      from lines l
      where not exists (select 1 from lines l2 where l2.previous_id = l.id)
      union all
      select l.previous_id, cte.last
      from cte join
           lines l
           on cte.id = l.id
     )
select cte.last, count(*)
from cte
group by cte.last;
他是一把小提琴

小提琴

精确地生成您的结果

如果你还想要第一个元素,比如你的标题状态,那是现成的

小提琴

精确地生成您的结果


如果您还需要第一个元素,如标题状态,则可以随时使用。

这里是Microsoft SQL Server 2016 db中的一个实现


下面是Microsoft SQL Server 2016数据库中的一个实现

我的第一个测试表明“column”cte.last“必须出现在GROUPBY子句中或在聚合函数中使用”。我的第一个测试表明“column”cte.last“必须出现在GROUPBY子句中或用于聚合函数”。这可能是我的错别字。
WITH chain
 AS (SELECT l.id AS [first], 
            l.id AS [last], 
            1 AS [len]
     FROM lines AS l
     WHERE l.previous_id IS NULL
     UNION ALL
     SELECT c.[first], 
            l.id, 
            c.[len] + 1 AS [len]
     FROM chain AS c
          JOIN lines AS l ON l.previous_id = c.[last]),
 result
 AS (SELECT DISTINCT 
            c.[first], 
            c.[last], 
            c.[len], 
            ROW_NUMBER() OVER(PARTITION BY c.[first] ORDER BY c.[len] DESC) AS rn
     FROM chain as c)
 SELECT r.[first], 
        r.[last], 
        r.[len]
 FROM result AS r
 WHERE r.rn = 1
 ORDER BY r.[first];