简体   繁体   中英

Recursive CTE and Count Info from recursive table

I have this table called tblLandAreas :

在此处输入图片说明

Level 1 = Bloq
Level 2 = Ships
Level 3 = Sides
Level 4 = Beds

Ship is a child of Bloq , Sides is a child of Ship and Bed is a child of Side .

And I need to show a report this way:

在此处输入图片说明

Only when _parentid is null

I have tried this but it is not working:

在此处输入图片说明

Try the following:

DECLARE @t TABLE
    (
      ID INT ,
      ParentID INT ,
      Level INT
    )
INSERT  INTO @t
VALUES  ( 1, NULL, 1 ),
        ( 29, NULL, 1 ),
        ( 38, 29, 2 ),
        ( 32, 1, 2 ),
        ( 18, 1, 2 ),
        ( 41, 29, 2 ),
        ( 42, 41, 3 ),
        ( 43, 41, 3 ),
        ( 44, 41, 3 ),
        ( 45, 44, 4 )

;WITH cte AS(SELECT *, id AS baseid FROM @t WHERE ParentID IS NULL
             UNION ALL
             SELECT t.*, c.baseid FROM cte c JOIN @t t ON c.ID = t.ParentID)
SELECT baseid, 
       SUM(CASE WHEN Level = 2 THEN 1 ELSE 0 END) ships,
       SUM(CASE WHEN Level = 3 THEN 1 ELSE 0 END) sides,
       SUM(CASE WHEN Level = 4 THEN 1 ELSE 0 END) beds
FROM cte
WHERE ParentID IS NOT NULL
GROUP BY baseid

Output:

baseid  ships   sides   beds
1       2       0       0
29      2       3       1

To project on your structure:

;WITH Bloque AS(SELECT LandAreaId, _ParentId, _Level, LandAreaId AS baseLandAreaId
                FROM tblLandAreas WHERE _ParentId IS NULL
                UNION ALL
                SELECT a.LandAreaId, a._ParentId, a._Level, B.baseLandAreaId
                FROM Bloque B 
                JOIN tblLandAreas a ON B.LandAreaId = a._ParentId)
SELECT baseLandAreaId AS LandAreaId, 
       SUM(CASE WHEN _Level = 2 THEN 1 ELSE 0 END) [#Ships],
       SUM(CASE WHEN _Level = 3 THEN 1 ELSE 0 END) [#Sides],
       SUM(CASE WHEN _Level = 4 THEN 1 ELSE 0 END) [#Beds]
FROM Bloque
WHERE _ParentId IS NOT NULL
GROUP BY baseLandAreaId

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM