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

标签 sql linq tsql recursion common-table-expression

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

假设您有以下数据:

ID   |  ParentID
-----------------
1    |   null
2    |   1
3    |   2
4    |   1
5    |   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/

相关文章:

sql - 如何在过滤后订购有很多关系

c# - Linq - 中断存储过程的执行

c# - 对排序列表进行分组而不影响 linq 中的排序

sql - 从 SQL 登录中提取密码

mysql - 使用css排列数据库中的数据

Android Ormlite - 使用条件 where 子句构建查询

sql - 如何获取 30 天内的下一个最小日期并用作 SQL 中的引用点?

c# - 在 Entity Framework linq 中两次包含相同字段时的行为

tsql - 从 CLR 存储过程访问 TSQL 创建的 #temp 表。是否可以?

SQL Server - 在每个组中添加页眉和页脚字段