使用嵌套回复对注释进行排序

时间:2012-04-09 16:28:27

标签: sql tsql

我正在尝试提出一个查询,它会在回复及其回复后返回评论。

这样的东西
comment 1
reply 1.1
reply 1.1.1
reply 1.2
comment 2
comment 3
comment 3.1 

到目前为止我有这个

SELECT [CommentID]
  ,[ParentID]
  ,[Message]
  , ROW_NUMBER() over(partition by ParentID order by CommentID ) as rn
  ,[CreatedBy]
  ,[CreatedDate]
  FROM [DBNAME].[dbo].[Commenttable] 
  GROUP BY [CommentID],[ParentID],[CreatedDate],[Message],[CreatedBy]

但我得到的是

comment 1
comment 2
comment 3
reply 1.1
reply 1.2
reply 3.1
reply 1.1.1

基本结构只是一个包含注释ID,父ID和消息的表。 评论和回复只是为了帮助解释我想要实现的目标

1 个答案:

答案 0 :(得分:3)

尝试一下:

declare @CommentTable as Table ( CommentId Int Identity, ParentId Int Null, Message VarChar(16) )
insert into @CommentTable ( ParentId, Message ) values
  ( null, '1' ),
  ( null, '2' ), ( 1, '1.1' ),
  ( null, '3' ), ( 4, '3.1' ), ( 3, '1.1.1' ), ( 1, '1.2' )
select * from @CommentTable

; with Cindy as (
  -- Start with the base comments.
  select CommentId, ParentId, Message, Row_Number() over ( order by CommentId ) as Number,
    Cast( Row_Number() over ( order by CommentId ) as VarChar(1000) ) as Path,
    Cast( Right( '0000' + Cast( Row_Number() over ( order by CommentId ) as VarChar(4) ), 5 ) as VarChar(1000) ) as OrderPath
    from @CommentTable
    where ParentId is NULL
  union all
  -- Add replies on layer at a time.
  select CT.CommentId, CT.ParentId, CT.Message, Row_Number() over ( order by CT.CommentId ),
    Cast( C.Path + '.' + Cast( Row_Number() over ( order by CT.CommentId ) as VarChar(4) ) as VarChar(1000) ),
    Cast( C.OrderPath + Right( '0000' + Cast( Row_Number() over ( order by CT.CommentId ) as VarChar(4) ), 5 ) as VarChar(1000) )
    from @CommentTable as CT inner join
      Cindy as C on C.CommentId = CT.ParentId
  )
  select *
    from Cindy
    order by OrderPath