I want to create hierarchical report in SSRS using this simple table? Could you please help me? I follow the tutorial here: https://www.mssqltips.com/sqlservertip/1939/working-with-a-parent-child-hierarchy-in-sql-server-reporting-services-ssrs/
but I can't figure out how the EmployeeKey and ParentEmployeeKey apply to my table. As far As my table concern Col2 Is the Employee and Col1 is the parent. But in SSRS when I group by Col2 and Recursive Parent is COL1 I don't get the desired result.
Here is my table:
╔══════════════╦══════════════╗
║ COL1 ║ COL2 ║
╠══════════════╬══════════════╣
║ TEST01 ║ TEST02 ║
║ TEST01 ║ TEST03 ║
║ TEST01 ║ TEST04 ║
║ TEST02 ║ LAB ║
║ TEST02 ║ STL40 ║
║ TEST03 ║ LABSTL ║
║ TEST03 ║ STLSCH40 ║
║ TEST04 ║ LABSTL ║
║ TEST04 ║ FLG41 ║
║ TEST04 ║ STLSCH40 ║
╚══════════════╩══════════════╝
This is the outcome that I want to get using SSRS. like indent style of the picture ..
╔═══════════════╦══╗
║ COL1 ║ ║
╠═══════════════╬══╣
║ TEST01 ║ ║
║ -TEST02 ║ ║
║ ----LAB ║ ║
║ ----STL40 ║ ║
║ -TEST03 ║ ║
║ ----LABSTL ║ ║
║ ----STLSCH40 ║ ║
║ -TEST04 ║ ║
║ ----LABSTL ║ ║
║ ----FLG41 ║ ║
║ ----STLSCH40 ║ ║
╚═══════════════╩══╝
I don't know to get the indent style result above. Do I need to use HierarchyID and IsDescendantOf or Recursive CTE. This is the Recursive CTE that I did and the result under it.
Declare @Col1 varchar(30)='TEST01';
Declare @BomLevel Integer=0;
WITH tBOM
AS
(
select a.Col1 , a.Col2, @BomLevel "BOMLevel" from Component A
WHERE Col1= @Col1
UNION ALL
Select c.Col1, c.Col2, BomLevel+1 From Component C
INNER JOIN tBOM on tBOM.Col2=c.Col1
)
select Col1,Col2 ,BOMLevel from tbom
Col1 Col2 BOMLevel
TEST01 TEST02 0
TEST01 TEST03 0
TEST01 TEST04 0
TEST02 STL40 1
TEST02 LAB 1
TEST03 STLSCH40 1
TEST03 LABSTL 1
TEST04 STLSCH40 1
TEST04 FLG41 1
TEST04 LABSTL 1
This should work for any depth (assuming you don't pass VARCHAR(50) for SORT_PATH). The 'Trick' while you are going down the hierarchy you build a string that you can sort by (SORT_PATH). At the end, we can use
REPLICATE()
with our BOMLevel to indent with something (in this case a hyphen).This seems like kind of a funky way to do it but I can't really think of a good way to output the results in the format you're expecting:
This outputs:
... But it makes the assumption that the maximum depth of any parent is 2 (as per the example). If you go deeper than that and you're not sure how deep it goes, then you'd need to use dynamic SQL to produce a similar result. Of note, I've answered a similar question to this in the following link, if you want to see how to produce a HTML list as output from a parent/child table: https://stackoverflow.com/a/34445701/5552667