我有一个如下表:
create table path(
id integer,
start varchar(255),
finish varchar(255),
client integer
);
INSERT INTO path(id, start, finish, client) VALUES (1, '1', '2', 1);
INSERT INTO path(id, start, finish, client) VALUES (2, '2', '3', 1);
INSERT INTO path(id, start, finish, client) VALUES (3, '3', '4', 1);
INSERT INTO path(id, start, finish, client) VALUES (4, '5', '6', 1);
我尝试了以下查询:
select string_agg(start || ' -> ' ||finish, ', ' order by id) from path group by client;
结果是这样的:
1 -> 2, 2 -> 3, 3 -> 4, 5 -> 6
如果两个序列值相同,如何获得以下结果:
1 -> 2 -> 3 -> 4, 5 -> 6
这里是Sql Fiddle link。
答案 0 :(得分:1)
如我的评论中所述,递归CTE将产生此结果。 As an example:
WITH RECURSIVE reccte AS
(
/*Recursive Seed - Records that will start recursion*/
SELECT id, start, finish, client, start || '->' || finish as path, 1 as depth
FROM path
WHERE id = 1
UNION ALL
/*Recursive Term - This will be the statement that iterates until the join fails*/
SELECT
path.id, path.start, path.finish, path.client, reccte.path || '->' || path.finish, depth + 1
FROM reccte
INNER JOIN path ON reccte.finish = path.start
WHERE depth < 20 /*make sure we don't loop endlessly*/
)
SELECT * FROM reccte;
+----+-------+--------+--------+---------------+-------+
| id | start | finish | client | path | depth |
+----+-------+--------+--------+---------------+-------+
| 1 | 1 | 2 | 1 | 1->2 | 1 |
| 2 | 2 | 3 | 1 | 1->2->3 | 2 |
| 3 | 3 | 4 | 1 | 1->2->3->4 | 3 |
| 4 | 4 | 5 | 1 | 1->2->3->4->5 | 4 |
+----+-------+--------+--------+---------------+-------+
在此示例中,最后一个SELECT
可以更改为SELECT path FROM reccte ORDER BY depth DESC LIMIT 1;
,以替换您想要的记录。
已更新:
这里的解决方案仍然相同,我们只是调整了递归CTE和最终选择,以获取层次结构的不同完整分支/路径:
http://sqlfiddle.com/#!17/2892f/6
WITH RECURSIVE reccte AS
(
SELECT id as origin, id, start, finish, client, start || ' -> ' || finish as path, 1 as depth
FROM path
WHERE start NOT IN (SELECT distinct finish FROM path)
UNION ALL
SELECT
reccte.origin, path.id, path.start, path.finish, path.client, reccte.path || ' -> ' || path.finish, depth + 1
FROM reccte
INNER JOIN path ON reccte.finish = path.start
WHERE depth < 20 /*make sure we don't loop endlessly*/
)
SELECT * FROM (SELECT origin, path, depth, max(depth) OVER (PARTITION BY origin) as maxdepth FROM reccte) sub WHERE sub.maxdepth = depth;
+--------+------------------+-------+----------+
| origin | path | depth | maxdepth |
+--------+------------------+-------+----------+
| 1 | 1 -> 2 -> 3 -> 4 | 3 | 3 |
| 4 | 5 -> 6 | 1 | 1 |
+--------+------------------+-------+----------+
您也可以在该最终选择中在此处string_agg(),以获取更新问题中的确切输出:
http://sqlfiddle.com/#!17/2892f/5
SELECT STRING_AGG(path, ', ' order by origin) FROM (SELECT origin, path, depth, max(depth) OVER (PARTITION BY origin) as maxdepth FROM reccte) sub WHERE sub.maxdepth = depth;
+--------------------------+
| string_agg |
+--------------------------+
| 1 -> 2 -> 3 -> 4, 5 -> 6 |
+--------------------------+