Question

Create a multi-level organisation chart / hierarchy from a single table

Asked by: dearsina

I have been given a table with about 3,500 records with the following headers (simplified for the sake of this exercise):

staffID | name | reportsToID


I have to create a report that presents this data in a hierarchical form, something like this:

FD
      FDSubordinate1
      FDSubordinate2
CIO
      CIOSubordinate1
            CIOSubSubordinate1
      CIOSubordinate2

Note that
- There are several top nodes (i.e. several people who do not have a boss)
- There is no limit to the number of sub-levels, but I doubt there are more than 9
- I wish to later perform some calculations with the numbers, so the output can't be in Visio etc.

What I'm looking for
The piece of VB (I assume) that along with a SQL query pulls out a workable output. What would be very useful would be sample db's if you've done similar things before.

I'm running Access 2003.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2006-01-23 at 10:34:44ID21706944
Tags

chart

Topic

Microsoft Access Database

Participating Experts
3
Points
500
Comments
22

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Hierarchical Trees
    I want to design a financial package around the chart of account of course; being the master table of such an application. My client has a special requirement: he wants his chart of account to be set up in a "Hierarchical Tree" fashion. Does anybody out there have...
  2. Export org chart from powerpoint to visio
    Is it possible to export an org chart in powerpoint to visio?
  3. Convert Visio 2003 organization chart to Word 2003 …
    Both Word 2003 and Visio 2003 have the "organization chart" component to build an org chart. Our admin inherited a visio org chart, but she's very uncomfortable working in visio. So I tried to "save as" or open it with Word, or copy and paste, etc. but c...
  4. Link Visio org chart
    I used the org chart wizard to construct my org chart. The data was from an excel file. Question: Is my drawing 'org chart' now linked to the excel file so that I can make changes to the file and it will be updated on the visio drawing? It doesn't seem to be working. ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: jimhornPosted on 2006-01-23 at 11:05:20ID: 15769329

AFAIK Access and VB do not have an Organizational Chart wizard that would connect to a data source and generate an Org Chart, as you have it displayed.

Perhaps Visio has this?

Hope this helps.
-Jim

 

by: nico5038Posted on 2006-01-23 at 11:36:20ID: 15769600

This self referring table can be used in a query where you place the table as many times as you have levels (+1) and join the  reportsToID to the staffID for all subsequent tables.
When filtering the first table for an empty reportsToID the start will be with the "roots".

Did you try this ?

The code solution would be to create a so-called recursive procedure taht's calling itself when a new "branch" is found.

Nic;o)

 

by: RgGray3Posted on 2006-01-23 at 11:42:24ID: 15769641

You can create a query using Reports to...  and builds a record set and do a grouping report...
You create a query that has TWO instances of the table and create the link between the ID and Reports to ID

Alias the name of the two tables   Mgr & Employee   or ReportsTo and Employee

and take the Name from the Manager as Manager  and take the Name from the Employee side as the employee

That said

Visio does have a OrgChart wizard that will take the data a build an orgchart

Rich

 

by: dearsinaPosted on 2006-01-24 at 04:21:24ID: 15774683

Nico/rich, I think you're both onto something, I have been reading a bit more about this and it seems like the ideal way of the output data is in a table like this:

Level1            Level2            Level3            LevelN
------------------------------------------------------------------------------------
FD            [NULL]            [NULL]            [NULL]
FD            FDSubordinate1      [NULL]            [NULL]
FD            FDSubordinate2      [NULL]            [NULL]
CIO            [NULL]            [NULL]            [NULL]
CIO            CIOSubordinate1      [NULL]            [NULL]
CIO            CIOSubordinate1      CIOSubSubordinate1      [NULL]
CIO            CIOSubordinate2      [NULL]            [NULL]

Because once this table/query has been set up, the report can deal with the formatting etc. I've found a similar EE question that might shed some light on the matter, I tried fishing some code out, but with little luck.

http://www.experts-exchange.com/Databases/MS_Access/Q_20768479.html

Perhaps someone can put together a query that I can use, I understand basic SQL theory/queries, but I'm afraid I'm a little lost with the SQL suggestions I've been given so far. Thanks for your patience.

 

by: RgGray3Posted on 2006-01-24 at 07:07:06ID: 15775937

The following is a simple example of the concept bringing 4 levels of org

Place 4 copies of the same table onto your SQL work area

Look at their property sheets and you will see a property called Alias

Rename each table with a simple and logical name (I used Level 1-4)

Bring the Name, (and any other field required) from each level
Rename each field with a simple and logical name (I Used LevelXName where X indicates the level)

Run the query and you see the data

Make a grouping report and you are on your way

----------------------------------------------------------------------------------------------

SELECT Level1.WPName AS Level1Name, Level2.WPName AS Level2Name, Level3.WPName AS Level3Name, Level4.WPName AS Level4Name
FROM WorkerProviders_tbl AS Level4 INNER JOIN (WorkerProviders_tbl AS Level3 INNER JOIN (WorkerProviders_tbl AS Level2 INNER JOIN WorkerProviders_tbl AS Level1 ON Level2.WPParent = Level1.WPID) ON Level3.WPParent = Level2.WPID) ON Level4.WPParent = Level3.WPID;

----------------------------------------------------------------------------------------------

Rich

 

by: RgGray3Posted on 2006-01-24 at 07:25:10ID: 15776159

Note: on the above
Each table has an ID Field 'WPID' and
Each Lower (higher number) level's WPParent points to the WPID of another record
If you are at the top level (this person reports to no one but themself...   The two fields are equal

Link each lower WPParent to the WPID of the parent table


1.WPID...2.WPParent      2.WPID... 3WPParent .....      etc

Rich

 

by: dearsinaPosted on 2006-01-24 at 09:08:09ID: 15777535

Rich, thank you for assisiting with my query. You have got my mind thinking about different ways of how we can solve this.
The problem with the above solution is that it assumes an equal length to the chains of command, ie. it only outputs the links which have n people in them (in this case 4), in addition, it fetches any link with four people, so a link with 5 people would be listed twice, first as 1-2-3-4 then 2-3-4-5.

I've done some more research and I think the answer is a recursive VB function that ties into a query and produces a table with n number of columns where n is the max number of columns. Anybody fancy having a go?

I've look at BOM (bill of materials) queries and a host of other solutions, but the general feeling is that the VB solution is the most efficient, particularly given that we don't know the number of levels.

A bit of background, the type of list I have is an adjacency list, because the connection between parent-child are adjecent to eachother. Oracle DBs have the abillity to query recursively, but MS SQL and by extention, Access does not.

Thanks again to those of your helping out.

 

by: nico5038Posted on 2006-01-24 at 09:26:03ID: 15777713

Hmm, guess you overlooked this sentence in my comment:

When filtering the first table for an empty reportsToID the start will be with the "roots".

Nic;o)

 

by: RgGray3Posted on 2006-01-24 at 11:07:57ID: 15778759

If you use an outter join it should return the shorter chains (an oversite since I am knee deep or better into another project)



Rich

 

by: dearsinaPosted on 2006-01-25 at 05:18:55ID: 15785656

Rich, I tried OUTER JOIN, but Access rejected it. I tried RIGHT JOIN, and got an insufficent result. I don't think this can be solved with a pure SQL solution.

In other news, I have now actually managed to solve this using a VB script and a query which takes the output from the script and breaks it into n number of columns (as the VB script only outputs the path in a single column). I was hoping for a more elegant solution, either pure SQL or a single VB script do produce a multi-column query.

I'm a bit unsure of what to do with the points for this question at this stage, as I haven't really gotten the answer I was looking for, although I haven't fully explored Nico's comment (I didn't fully understand how to implement the solution). I will leave it open for a couple of days and see if someone has an ingenious solution to this issue.

Thank you for your help so far.

 

by: nico5038Posted on 2006-01-25 at 09:05:36ID: 15788022

Just place all your tables (one for each level) and place for each the fields staffID, name and reportsToID.
Now place under the first table's reportsToID the criteria:
Is Null

This will make sure that only staff without a "reports to" will be the first visible level.

Nic;o)

 

by: dearsinaPosted on 2006-02-08 at 14:01:25ID: 15907270

I've solved this using a vb script and a couple of funny little queries, if you're here looking for the answer to my question, have a look here:

http://www.experts-exchange.com/Databases/MS_Access/Q_20768479.html

With regards to the points, I'm happy to let you guys decide who gets what. Keep me posted.

 

by: nico5038Posted on 2006-02-08 at 14:25:03ID: 15907536

Hmm, looks very slow to me using a function with DLOOKUP(). Would be better to use a recursive recordset processing loop.
But as it's solved, just ask in CS (http://www.experts-exchange.com/Community_Support/) to delete/refund this question.

Nic;o)

 

by: dearsinaPosted on 2006-02-08 at 14:43:42ID: 15907743

Nico, do you have any code snippets? As you mentioned, the code above is indeed slow, and I'm afraid it will break once I give it the 3000+ recordset, so any improvements would be very welcome.

 

by: nico5038Posted on 2006-02-09 at 09:55:45ID: 15914927

A recursive procedure will call itself when discovering a "ReportsToID".
Assuming your table is named "tblStaff" with the above mentioned fields, these functions should do the job:

Function fncMain()
' function to process all persons from the table
Dim rs As DAO.Recordset

Set rs = CurrentDb.openrecordset("select * from tblStaff")
While Not rs.EOF
   Debug.Print fncRecur(rs!staffid)
   rs.MoveNext
Wend

End Function


Function fncRecur(strReportsToID As String) As String
' function to construct the higher levels offered person
Dim rs As DAO.Recordset

Set rs = CurrentDb.openrecordset("select * from tblStaff where StaffID='" & strReportsToID & "'")
' test found, else exit
If rs.EOF And rs.BOF Then Exit Function
' process
While Not rs.EOF
   If IsNull((rs!reportstoid)) Then
      fncRecur = fncRecur & ";" & rs!Name
      fncRecur = Mid(fncRecur, 2)
   Else
      ' no "root" so get higher level person
      fncRecur = fncRecur(rs!reportstoid) & ";" & rs!Name
   End If
   rs.MoveNext
Wend

End Function

Nic;o)

 

by: dearsinaPosted on 2006-02-14 at 05:38:08ID: 15950721

Either I'm doing something wrong, or that code just doesn't work. It seems to assume that every boss has to have his own line (where the boss appears as the employee). This won't work, because there will be people who are only bosses, and not "employees", for instance the CEO.

Any thoughts?

 

by: nico5038Posted on 2006-02-14 at 09:31:28ID: 15952859

I tested with:
StaffID                    Name      ReportsToID
FD                     FD Name      
FDSubordinate1      FDSubordinate1 Name      FD
FDSubordinate2      FDSubordinate2 Name      FD
CIO                     CIO Name      
CIOSubordinate1      CIOSubordinate1 Name      CIO
CIOSubordinate2      CIOSubordinate2 Name      CIO
CIOSubSubordinate1      CIOSubSubordinate1 Name      CIOSubordinate1

Giving:
FD Name
FD Name;FDSubordinate1 Name
FD Name;FDSubordinate2 Name
CIO Name
CIO Name;CIOSubordinate1 Name
CIO Name;CIOSubordinate2 Name
CIO Name;CIOSubordinate1 Name;CIOSubSubordinate1 Name

Thought that was the intention...

Nic;o)

 

by: dearsinaPosted on 2006-02-16 at 02:18:46ID: 15969560

Nico,

You are very right, my apologies, it works like a charm, Is there a way of outputting the data to a datasheet? Or better yet, just doubleclick on a query sheet which runs the module and outputs the data in its data sheet?

 

by: nico5038Posted on 2006-02-16 at 09:30:06ID: 15972939

Just define a table tblOutput with an autonumberID and a memo field named "Staff" and change:

   Debug.Print fncRecur(rs!staffid)

into:

   currentdb.execute ("insert into tblOutput (Staff) values ('" & fncRecur(rs!staffid) & "')")

Nic;o)

 

by: dearsinaPosted on 2006-03-10 at 08:40:11ID: 16156147

Further to Nico's comments, if you want to break the data up into different cells, I am sure there are cleverer ways of doing it, but one quick and dirty way would be to run a query which in turn runs this script:

Function SplitIt(pFullName As String, pPosition As Integer) As String
  Dim HoldArr() As String
  HoldArr = Split(pFullName, " > ")
If (pPosition - 1 <= UBound(HoldArr)) Then
    SplitIt = HoldArr(pPosition - 1)
    End If
End Function

The query should have the following in each cell:

Level1: SplitIt([Reference],1)

Where "Level1" is the title of the column, "SplitIt" is the name of the script called "[Reference]" is the name of the cell being split up (or using the names Nicohas been using replace it with "[Staff]") and finally the "1" is the part of the string (e.g. each ";" increasing the value by 1) you want to put into the cell, so that the column called Level1 would be 1, the column called Level2 would be 2 and so on, so that:

Boss;Subordinate;SubSubordinate

Becomes
Level1|Level2|Level3
Boss|Subordinate|SubSubordinate
(Where the "|" deliminates cell change)

I don't know if the above made any sense, if not, just comment here and I'll be notified. Right now I'm so hungry that I'm close to passing out.

 

by: dearsinaPosted on 2006-03-13 at 11:13:14ID: 16176856

I gave the points too quickly... The script gives an error when you introduce it to a large dataset (1600 records):

Run-time error '3048' Cannot open any more databases.

It highlights the following line:

Set rs = CurrentDb.OpenRecordset("select * from tblStaff where StaffID='" & strReportsToID & "'")

Having read up on it, it seems there is a limit of 2048 of the number of tableIDs Access can dish out. Now, I'm sure there must be a way to close the recordsets once they've been used, I don't seem to figure out where, and with what command.

Any suggestions? I'm happy to award additional points for the answer, lots of them too if I it comes quickly... :-)

sina
london

 

by: nico5038Posted on 2006-03-13 at 11:37:40ID: 16177055

Try:

Function fncRecur(strReportsToID As String) As String
' function to construct the higher levels offered person
Dim rs As DAO.Recordset

Set rs = CurrentDb.openrecordset("select * from tblStaff where StaffID='" & strReportsToID & "'")
' test found, else exit
If rs.EOF And rs.BOF Then Exit Function
' process
While Not rs.EOF
   If IsNull((rs!reportstoid)) Then
      fncRecur = fncRecur & ";" & rs!Name
      fncRecur = Mid(fncRecur, 2)
   Else
      ' no "root" so get higher level person
      fncRecur = fncRecur(rs!reportstoid) & ";" & rs!Name
   End If
   rs.MoveNext
Wend
set rs = Nothing

End Function

Nic;o)

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...