I’ve been given a SQL table that has a parent-child relationship that I’d like to present in a readable format.
The main columns involved are Drawer, Folder, Document. Each Drawer can have multiple folders associated to it, and each folder can have multiple documents associated to it. However, the Folder and Document are not listed in the same record.
This table contains item types, and a folder and document are both considered items. To associate them, the table assigns the itemnumber of the folder to the parentID in the document record.
For example:
DrawerID ItemID ParentID Type Name
1 1 0 Folder Folder 1
1 2 0 Folder Folder 2
1 3 0 Folder Folder 3
1 4 0 Folder Folder 4
1 5 1 Document Document A
1 6 1 Document Document B
1 7 1 Document Document C
1 8 2 Document Document A
1 9 3 Document Document A
1 10 3 Document Document B
What I’m looking for is an output similar to this:
Drawer 1
Folder 1
Document A
Document B
Document C
Folder 2
Document A
Folder 3
Document A
Document B
The part that I’m stuck on is how to tie the ParentID to the ItemID. Would the best approach be some sort of union? recursive programming into a new table? I’m not a SQL person – I just cut and paste bits of queries, so please use little words 🙂
This query should work, tested OK in SQL Server on your data. Basically it’s creating two pseudo tables in the query to represent the Folder and Document entities then joining together on the parent relationship: