gpt4 book ai didi

sql - 递归SQL CTE和自定义排序顺序

转载 作者:行者123 更新时间:2023-12-04 04:01:37 29 4
gpt4 key购买 nike

您正在为线程讨论板创建DB模式的镜像。有没有一种有效的方法来为给定线程选择适当排序的列表?我编写的代码行得通,但并没有按照我想要的方式进行排序。

假设您有以下数据:

ID   |  ParentID-----------------1    |   null2    |   13    |   24    |   15    |   3

So the structure is supposed to look like this:

1|- 2|  |- 3|  |  |- 5|- 4

Ideally, in the code, we want the result set to appear in the following order: 1, 2, 3, 5, 4
PROBLEM: With the CTE I wrote it is actually being returned as: 1, 2, 4, 3, 5

I know this would be easy to group/order by using LINQ but I am reluctant to do this in memory. It seems like the best solution at this point though...

Here is the CTE I am currently using:

with Replies as (   
select c.CommentID, c.ParentCommentID 1 as Level
from Comment c
where ParentCommentID is null and CommentID = @ParentCommentID

union all

select c.CommentID, c.ParentCommentID, r.Level + 1 as Level
from Comment c
inner join Replies r on c.ParentCommentID = r.CommentID
)

select * from Replies

任何帮助,将不胜感激;谢谢!

我是SQL的新手,之前从未听说过architectureid数据类型。从 this comment阅读了有关它的信息后,我决定我可能要将其合并到我的设计中。今晚我将对此进行试验,如果成功,我会发布更多信息。

更新
使用dance2die的建议从我的样本数据返回的结果:

ID | ParentID |级别|密集排名
-------------------------------------
15空1 1
20 15 2 1
21 20 3 1
17 22 3 1
22 15 2 2
31 15 2 3
32 15 2 4
33 15 2 5
34 15 2 6
35 15 2 7
36 15 2 8

最佳答案

我相信您会喜欢
我最近发现了Dense_Rank()函数,它根据MSDN用于“在结果集的分区内排名”

查看下面的代码以及“CommentID”的排序方式。

据我了解,您正在尝试按ParentCommentID对结果集进行分区。

注意“denserank”列。

with Replies (CommentID, ParentCommentID, Level) as 
(
select c.CommentID, c.ParentCommentID, 1 as Level
from Comment c
where ParentCommentID is null and CommentID = 1

union all

select c.CommentID, c.ParentCommentID, r.Level + 1 as Level
from Comment c
inner join Replies r on c.ParentCommentID = r.CommentID
)
select *,
denserank = dense_rank() over (partition by ParentCommentID order by CommentID)
from Replies
order by denserank

结果如下

关于sql - 递归SQL CTE和自定义排序顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/566061/

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