I have a table representing a folder structure - (i.e recursion on id and parent field) - this data actually represents items within a folder structure (the item field is simply there for the example, however my case will be a join to many items. I have created a path string (does not need to be used) - this string represents the path of each record in the data-set(branch field)
my query needs to filter by all records that are more than 3 levels deep, then count any items that are at 3 levels or lower in each recursion branch ( in my data, this would mean records 5 & 6 represent top level nodes and will be records used for the grouping.
Any assistance?
DECLARE @tbl TABLE
(
Id int
,ParentId int
,branch varchar(100)
,depth int
,item varchar(20)
)
INSERT INTO @tbl
( Id, ParentId,item )
VALUES
(1, NULL,Null),
(2, 1,Null),
(3, 1,Null),
(4, 3,Null),
(5, 4,Null),
(6, 5,'car'),
(7, 6,'bus'),
(8, 7,'truck'),
(9, 8,'car'),
(10,8,'bike'),
(11,5,'car'),
(12,5,'truck'),
(13,4,'truck'),
(14,8,'bike'),
(15,8,'bus');
--select t_package.package_id, t_package.parent_ID from t_package
;WITH abcd
AS (
-- anchor
SELECT id
,ParentID
,CAST(id AS VARCHAR(100)) AS [Path]
,0 as depth
,item
FROM @tbl
WHERE ParentId is Null
UNION ALL
--recursive member
SELECT t.id
,t.ParentID
,CAST(a.[Path] + ',' + CAST( t.ID AS VARCHAR(100)) AS varchar(100)) AS [Path]
,a.depth +1
,t.item
FROM @tbl AS t
JOIN abcd AS a ON t.ParentId = a.id
)
insert into @tbl (id,parentID,branch,depth,item) select * from abcd
select * from @tbl
where branch is not null
This would mean that if you grouped at level 3, and required the counts of items at each level, your result set would look something like this:
ID Depth -- car -- bike -- bus -- truck
5 3 -- 3 -- 2 -- 2 -- 2
13 3 -- 0 -- 0 -- 0 -- 1
depthis accurate, all you really need to do is agroup byon depth.