declare @Comment table(commentId int, parentId int, message varchar(20))
insert into @Comment
select 1, 0,'my comment 1' union all
select 2, 0,'mu comment 2' union all
select 3, 1,'reply 1.1' union all
select 4, 1,'reply 1.2' union all
select 5, 1,'reply 1.3' union all
select 6, 1,'reply 1.4' union all
select 7, 1,'reply 1.5' union all
select 8, 2,'reply 2.1' union all
select 9, 2,'reply 2.2' union all
select 10,2,'reply 2.3' union all
select 11,2,'reply 2.4'
;with C as
(
select commentId,
parentId,
message,
row_number() over(partition by parentId order by commentId desc) as rn
from @Comment
)
select C.commentId,
C.parentId,
C.message
from C
where C.parentId = 0 or C.rn <= 3
order by C.commentId
Result:
commentId parentId message
----------- ----------- --------------------
1 0 my comment 1
2 0 mu comment 2
5 1 reply 1.3
6 1 reply 1.4
7 1 reply 1.5
9 2 reply 2.2
10 2 reply 2.3
11 2 reply 2.4