【发布时间】:2020-12-21 18:26:43
【问题描述】:
*我很抱歉,当我写这个问题时,我的表格显示正确,并且在发布格式后看起来不正常。现在尝试解决这个问题
我正在尝试在 postgresql 中编写一个查询,对于任何给定的子值,该查询将返回已达到某个等级的最近的父值。目前,我有这个查询,它显示任何给定子值的整个层次路径-
WITH RECURSIVE tree AS (
SELECT "ChildDisplayID",
"ParentID",
"Rank",
1 as level
FROM table1
WHERE "ChildDisplayID" = {{some ChildID}}
UNION ALL
SELECT t1."ChildDisplayID",
t1."ParentID",
t1."Rank",
t.level + 1
FROM table1 t1
JOIN tree t ON t."ParentID" = t1."ChildDisplayID"
)
SELECT *
FROM tree
我想要做的是在单行中显示排名为“合作伙伴”的最近父母的子 ID 和父 ID。例如,这是我目前得到的输出:
| ChildID | ParentID | Rank | Level |
|---------|----------|------|-------|
| 6 | 5 |Associate Manager| 1 |
| 5 | 4 |Manager| 2 |
| 4 | 3 |Associate Partner| 3 |
| 3 | 2 |Partner| 4 |
| 2 | 1 |Partner| 5 |
| 1 | |CEO| 6 |
这是我想要的输出:
|ChildID | Nearest Partner | Rank |
|--------|----------|------|
|6 |3 | Partner |
最好的方法是什么?
【问题讨论】:
标签: sql postgresql common-table-expression hierarchical-data recursive-query