我有一个名为tblLandAreas
的表:
Level 1 = Bloq
Level 2 = Ships
Level 3 = Sides
Level 4 = Beds
Ship
是Bloq
的孩子,Sides
是Ship
的孩子,Bed
是Side
的孩子。
我需要以这种方式展示报告:
仅在_parentid is null
我试过这个,但它不起作用:
答案 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