1

我正在尝试提出一个查询,该查询将在他们的回复及其回复之后返回评论。

就像是

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

ETC

到目前为止我有这个

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 和消息的表。评论和回复只是为了帮助解释我想要实现的目标

4

1 回答 1

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
于 2012-04-09T17:57:51.030 回答