I’m building a forum. Now I would like to create a query that returns the number of reactions on each post. A reaction is defined as all the posts under a certain post. I would like to use CTE to achieve this.
So fare I’ve got this:
;WITH Reaction(Cnt, ParentId) AS
(
SELECT COUNT(*), ParentId
FROM dbo.Post
GROUP BY ParentId
)
SELECT ISNULL(Cnt, 0), Post.*
FROM dbo.Post Post
LEFT JOIN Reaction
ON Reaction.ParentId = Post.PostId
This is listing all the ‘direct’ posts. Now I’ve got to make this query count the entire tree, but I’m stuck. I’ve been reading a bit on CTE and I know you can make recursive queries, but I don’t know how to solve the problem of creating a recursive query that counts.
Something like this:
Edit, updated with in-line count