来自递归表的递归CTE和计数信息

时间:2015-06-24 12:08:38

标签: sql database recursion common-table-expression

我有一个名为tblLandAreas的表:

enter image description here

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

ShipBloq的孩子,SidesShip的孩子,BedSide的孩子。

我需要以这种方式展示报告:

enter image description here

仅在_parentid is null

我试过这个,但它不起作用:

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

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

输出:

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

投影你的结构:

;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