![](/img/trans.png)
[英]Postgresql query to return number of customers that made more than 1 order in a month
[英]Postgresql - Reformat Query return order
我有一個遞歸查詢,它返回一個非線性樹,但它首先返回所有的根節點。 (其中parent_id為null)
我如何排序查詢中獲取一個根節點,獲取整個樹的行,然后獲取第二個根節點,然后獲取整個樹...等等。
With RECURSIVE cte AS
(
(
SELECT *
FROM comments
WHERE thread_id = 1
AND parent_id is NULL
ORDER BY upvoted DESC
FETCH FIRST 10 ROW ONLY
)
UNION
SELECT t.*
From comments t
JOIN cte rt ON rt.comment_id = t.parent_id
)
SELECT cte.comment_id, cte.date_posted, cte.posted_by, cte.posted_by_user, cte.thread_id,
cte.parent_id, cte.comments, cte.post_title, cte.posted_to_group, cte.upvoted, cte.downvoted,
cte.depth, cv.user_id, cv.vote, cv.thread_id
from cte LEFT JOIN
commentsvoted cv
ON cte.comment_id = cv.id
AND cv.user_id = '82411580-6355-490e-be79- e7db9f561f66'
如果我添加:
ORDER BY coalesce(parent_id, comment_id), comment_id
到我的最后選擇,它返回我所描述的內容, 但忽略:
ORDER BY upvoted DESC
您可以按以下order by
使用窗口功能:
ORDER BY MAX(upvoted) OVER (PARTITION BY coalesce(parent_id, comment_id)) DESC,
coalesce(parent_id, comment_id), -- keep this in the event of ties,
(case when parent_id is null then 1 else 0 end),
comment_id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.