1
次のクエリを使用して、親アイテムと(最初の2つのみ)子孫を子カウントとともに返します。ただし、クエリは2つ以上の子孫を返します(ここではSQL Fiddle:http://sqlfiddle.com/#!6/6489b/5)。CTE再帰、親あたり一定数の子孫を取得する
;WITH cte AS (
SELECT [EntryId],
[Title],
[ParentId],
[Depth],
ROW_NUMBER() OVER (ORDER BY Date DESC) [Rn],
CAST(EntryId AS VARCHAR(MAX)) [Path],
1 AS DescendentCount
FROM ViewEntryRecords
WHERE [Depth] = 0 AND DiscussionWallId = @DiscussionWallId
UNION ALL
SELECT e.[EntryId],
e.[Title],
e.[ParentId],
e.[Depth],
Rn,
[Path] + ',' + CAST(e.EntryId AS VARCHAR(MAX)),
P.DescendentCount + 1
FROM ViewEntryRecords S
JOIN cte P ON P.EntryId = S.ParentId
WHERE S.Depth=0 AND P.DescendentCount <= 2
)
SELECT [EntryId],
[Title],
[ParentId],
[Depth],
ChildCount,
DescendentCount
FROM cte c1
OUTER APPLY (SELECT COUNT (*) - 1 AS ChildCount
FROM cte c2
WHERE c2.[Path] LIKE c1.[Path] + '%'
) oa
WHERE Rn BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1
ORDER BY c1.[ParentId], Date DESC
ここに出力があります。私はテストのためDescendentCountが含ま:
EntryId Title ParentId Depth ChildCount DescendentCount
15 a NULL 0 5 1
4 d NULL 0 1 1
1 c NULL 0 7 1
1 s NULL 0 7 1
22 a1 4 1 0 2
24 da 15 1 0 2
23 32 15 1 0 2
16 b 15 1 2 2
21 n 16 1 0 3
20 y 16 1 0 3
したがって、IDのエントリ:16が表示されなければならない私はP.DescendentCount < = 2条件を使用するからです。しかし、私はDescendentCountが私の思うように増加していないことを知っています。子孫のアイテムを制限する方法はありますか?
テストするデータを提供できますか? – Stainy
@Stainyあなたは本当のデータを意味しますか?どうやってやるの? – renakre
サンプルデータを使用して[SQL Fiddle](http://sqlfiddle.com/)を作成することをお勧めします。 –