I have a forum database that stores forum information in a single column. The forum allows for unlimited subforums.
Table name - forums
| ForumID | ParentForumID | Name | Description | TopicCount | ReplyCount | LastPost |
Given a ForumID
as a parameter I am trying to SUM
the TopicCount
and ReplyCount
for all child entries. I am also trying to return the latest LastPost
, which is specified as DATETIME
.
I've searched google and this forum and understand I should be using a recursive CTE but am having some difficulty understanding the syntax. Here is my CTE - work in progress.
WITH CTE (ForumID, ParentForumID)
AS
(
SELECT ForumID AS Descendant, ParentForumID as Ancestor
FROM forums
UNION ALL
SELECT e.Ancestor
FROM
CTE as e
INNER JOIN CTE AS d
ON Descendant = d.ParentForumID
)
SELECT e.Descendant, SUM(TopicCount) AS topics, SUM(ReplyCount) AS replys
FROM CTE e
WHERE e.Ancestor = 1
Where 1 = Parameter for the forum ID.
Thanks in advance for the help!
You're doing OK - you're quite close :-)
Basically, you need to:
TopicCount
andReplyCount
countersSo your code should look something like this:
Of course, you could wrap this into a stored procedure that would take the initial "root"
ForumID
as a parameter .