How to calculate the sum of values in a tree using SQL

后端 未结 9 2539
耶瑟儿~
耶瑟儿~ 2021-01-05 09:29

I need to sum points on each level earned by a tree of users. Level 1 is the sum of users\' points of the users 1 level below the user. Level 2 is the Level 1 points of the

9条回答
  •  北荒
    北荒 (楼主)
    2021-01-05 09:50

    Ok, this gives you the results you are looking for, but there are no guarantees that I didn't miss something. Consider it a starting point. I used SQL 2005 to do this, SQL 2000 does not support CTE's

    WITH Parent (id, GrandParentId, parentId, Points, Level1Points, Level2Points)
    AS
    (
        -- Find root
        SELECT id,  
                0 AS GrandParentId,
                ParentId,
                Points,
                0 AS Level1Points,
                0 AS Level2Points
        FROM tblPoints ptr
        WHERE ptr.ParentId = 0
    
        UNION ALL (
        -- Level2 Points
        SELECT pa.GrandParentId AS Id,
                NULL AS GrandParentId,
                NULL AS ParentId,
                0 AS Points, 
                0 AS Level1Points,
                pa.Points  AS Level2Points
        FROM tblPoints pt
                JOIN Parent pa ON pa.GrandParentId = pt.Id 
        UNION  ALL
        -- Level1 Points
        SELECT pt.ParentId AS Id,
                NULL AS GrandParentId,
                NULL AS ParentId,
                0 AS Points, 
                pt.Points AS Level1Points,
                0 AS Level2Points
        FROM tblPoints pt
                JOIN Parent pa ON pa.Id = pt.ParentId AND pa.ParentId IS NOT NULL 
        UNION  ALL
        -- Points
        SELECT pt.id,
                pa.ParentId AS GrandParentId,
                pt.ParentId,
                pt.Points, 
                0 AS Level1Points,
                0 AS Level2Points
        FROM tblPoints pt
                JOIN Parent pa ON pa.Id = pt.ParentId AND pa.ParentId IS NOT NULL )
    )
    SELECT id, 
        SUM(Points) AS Points,  
        SUM(Level1Points) AS Level1Points,
        CASE WHEN SUM(Level2Points) > 0 THEN  SUM(Level1Points) + SUM(Level2Points) ELSE 0 END AS Level2Points
    FROM Parent
    GROUP BY id 
    ORDER by id
    

提交回复
热议问题