I have a forum database that stores forum information in one column. Forum allows unlimited subforums.
Table Name - Forums
| ForumID | ParentForumID | Name | Description | TopicCount | ReplyCount | LastPost |
Given ForumID as a parameter, I try SUM TopicCount and ReplyCount for all children. I am also trying to return the last LastPost that is listed as DATETIME .
I searched google and this forum and understand that I have to use a recursive CTE, but it's hard for me to understand the syntax. Here is my CTE job.
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 identifier.
Thanks in advance for your help!
source share