gpt4 book ai didi

postgresql - 类似 row_number 的方法,每组从 0 开始

转载 作者:行者123 更新时间:2023-11-29 11:57:32 25 4
gpt4 key购买 nike

假设有一个表存储这样的层次结构:

item_id | hierarchical_id 
--------+-----------------
1 | ;1;
2 | ;1;2;
3 | ;1;2;3;
4 | ;1;2;4;
5 | ;1;2;4;5;

这里存储的层次结构是 1 作为根,2 是 1 的 child ,3 和 4 是 2 的 child ,5 是 4 的 child 。

查询

SELECT
-- the substr is used to remove the first and last semicolumns
regexp_split_to_table(substr(hierarchical_id, 2, length(hierarchical_id) - 2)
, E';'
) as parent_id,
item_id,
hierarchical_id
FROM
table

返回

parent_id | item_id | hierarchical_id
----------+---------+-----------------
1 | 1 | ;1;
1 | 2 | ;1;2;
2 | 2 | ;1;2;
1 | 3 | ;1;2;3;
3 | 3 | ;1;2;3;
1 | 4 | ;1;2;3;
2 | 4 | ;1;2;4;
4 | 4 | ;1;2;4;
1 | 5 | ;1;2;4;5;
2 | 5 | ;1;2;4;5;
4 | 5 | ;1;2;4;5;
5 | 5 | ;1;2;4;5;

如何修改查询以获得第 4 列,如下所示:

parent_id | item_id | hierarchical_id | distance
----------+---------+-----------------+---------
1 | 1 | ;1; | 0
1 | 2 | ;1;2; | 1
2 | 2 | ;1;2; | 0
1 | 3 | ;1;2;3; | 2
2 | 3 | ;1;2;3; | 1
3 | 3 | ;1;2;3; | 0
1 | 4 | ;1;2;4; | 2
2 | 4 | ;1;2;4; | 1
4 | 4 | ;1;2;4; | 0
1 | 5 | ;1;2;4;5; | 3
2 | 5 | ;1;2;4;5; | 2
4 | 5 | ;1;2;4;5; | 1
5 | 5 | ;1;2;4;5; | 0

distance的含义是当前行的item_idparent_id之间的距离。例如:一个节点到它自己的距离是0,一个节点到它的父节点的距离是1,一个节点到它的父节点的距离是2等等。它不一定要从0开始。

row_number 如果我能让它在每组相等的 item_id 的 0 处重新启动,那么 row_number 会工作正常,因为 hierarchical_id 中的 id已订购。

有什么建议吗?

最佳答案

窗口函数给你很多控制;见4.2.8. Window Function Calls .

你需要的关键是:

row_number() OVER (PARTITON BY item_id ORDER BY hierarchical_id)

给定数据:

create table t ( item_id integer, hierarchical_id text );
insert into t (item_id, hierarchical_id) values
(1,';1;'),
(2,';1;2;'),
(3,';1;2;3;'),
(4,';1;2;4;'),
(5,';1;2;4;5;');

查询:

WITH x AS (
SELECT regexp_split_to_table(substr(hierarchical_id, 2, length(hierarchical_id) - 2), E';') as parent_id,
item_id,
hierarchical_id
FROM t
)
SELECT
*,
row_number() OVER (PARTITION BY item_id ORDER BY parent_id DESC) - 1 AS distance
FROM x
ORDER BY item_id, parent_id;

产生:

 parent_id | item_id | hierarchical_id | distance 
-----------+---------+-----------------+----------
1 | 1 | ;1; | 0
1 | 2 | ;1;2; | 1
2 | 2 | ;1;2; | 0
1 | 3 | ;1;2;3; | 2
2 | 3 | ;1;2;3; | 1
3 | 3 | ;1;2;3; | 0
1 | 4 | ;1;2;4; | 2
2 | 4 | ;1;2;4; | 1
4 | 4 | ;1;2;4; | 0
1 | 5 | ;1;2;4;5; | 3
2 | 5 | ;1;2;4;5; | 2
4 | 5 | ;1;2;4;5; | 1
5 | 5 | ;1;2;4;5; | 0

这看起来大致正确,但由于您的预期输出似乎与我运行它时提供的查询输出不匹配(第 9.1 页),所以很难确定。

关于postgresql - 类似 row_number 的方法,每组从 0 开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12835025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com