The Wayback Machine - https://web.archive.org/web/20100104105926/http://beyondrelational.com/blogs/tc/archive/2009/12/14/tsql-challenge-19-working-with-consolidated-calculations-on-hierarchical-structures.aspx

TSQL Challenges

TSQL Challenges intend to help you to test and enhance SET based querying skills using TSQL.





TSQL Challenge 19 - Working with consolidated calculations on hierarchical structures

Working with hierarchies is almost always lot of fun for most of us. Traversing heirarchies and processing data from child or parent nodes is really interesting and such assignments are ideal opportunities to test your logic and query writing skills.

This challenge involves generating an organizational hierarchy and calculating the total orders created by each employee and his/her subordinates. It involves a number of challenges such as generating a resultset in the correct hierarchical form, calculating the orders created by each employee and his/her subordinates and finally calculating the total orders created by self and all the subordinates.

The new and improved evaluation process

We have been working on making the evaluation process more efficient and transparent. As a result, we came up with a 4 step evaluation process which we have described in detail in this post. We are also working on speeding up the evaluation process and we hope to catch up with the evaluation in a few weeks.

Help us to speed up the evaluation process

There are a number of things you could do to help us make the evaluation process faster. The first of that is following all the guidelines and rules given in the challenge. If you follow the guidelines, it will help us to complete the evaluation process faster.

When you submit a solution, do not include the code to generate the sample data. So, ideally your query should start with a SELECT or WITH and nothing else. No SET statements, NO setup or clean-up code. Our evaluation process will inject the required code into your solution while processing your solution. Please note that by following these guidlines, you are helping us to complete the evaluation process sooner.

Please pay attention!

Please pay attention to the rules given at the end of the challenge and the submission guidelines. We currently accept only SET based soutions with a single TSQL query. CTEs are accepted but temp tables, table variables, WHILE loops or UDFs are currently not accepted. A large number of submissions in the previous challenges were rejected because of these reasons. We are working on the evaluation process to see if we can support NON-SET based solutions in the future and we are quite hopeful that we will do it in the future.

Sample Data for TSQL Challenge 19

Employee Table

01.EmployeeID  FirstName       LastName        ReportsTo
02.----------- --------------- --------------- -----------
03.2           Andrew          Fuller          NULL
04.1           Nancy           Davolio         2
05.3           Janet           Leverling       2
06.4           Margaret        Peacock         2
07.5           Steven          Buchanan        2
08.8           Laura           Callahan        2
09.6           Michael         Suyama          5
10.7           Robert          King            5
11.9           Anne            Dodsworth       5

Order Table

01.OrderID     EmployeeID
02.----------- -----------
03.10258       1
04.10270       1
05.10275       1
06.10265       2
07.10277       2
08.10251       3
09.10253       3
10.10256       3
11.10250       4
12.10252       4
13.10248       5
14.10254       5
15.10249       6
16.10289       7
17.10303       7
18.10308       7
19.10262       8
20.10268       8
21.10276       8
22.10278       8
23.10255       9
24.10263       9

Expected Output

01.Name                      Level by_self by_sub total
02.------------------------- ----- ------- ------ -----
03.Fuller, Andrew            0     2       20     22
04.    Buchanan, Steven      1     2       6      8
05.        Dodsworth, Anne   2     2       0      2
06.        King, Robert      2     3       0      3
07.        Suyama, Michael   2     1       0      1
08.    Callahan, Laura       1     4       0      4
09.    Davolio, Nancy        1     3       0      3
10.    Leverling, Janet      1     3       0      3
11.    Peacock, Margaret     1     2       0      2

Scripts

Use the following script to generate the sample data

01.DECLARE @emp TABLE (
02.    EmployeeID INT,
03.    FirstName VARCHAR(15),
04.    LastName VARCHAR(15),
05.    ReportsTo INT
06.)
07. 
08.DECLARE @ord TABLE (
09.    OrderID INT,
10.    EmployeeID INT
11.)
12. 
13.INSERT INTO @emp(EmployeeID, FirstName, LastName, ReportsTo)
14.SELECT 2,'Andrew','Fuller',NULL UNION ALL
15.SELECT 1,'Nancy','Davolio',2 UNION ALL
16.SELECT 3,'Janet','Leverling',2 UNION ALL
17.SELECT 4,'Margaret','Peacock',2 UNION ALL
18.SELECT 5,'Steven','Buchanan',2 UNION ALL
19.SELECT 8,'Laura','Callahan',2 UNION ALL
20.SELECT 6,'Michael','Suyama',5 UNION ALL
21.SELECT 7,'Robert','King',5 UNION ALL
22.SELECT 9,'Anne','Dodsworth',5
23.SELECT * FROM @emp
24. 
25.INSERT INTO @ord (OrderID, EmployeeID)
26.SELECT 10258,1 UNION ALL
27.SELECT 10270,1 UNION ALL
28.SELECT 10275,1 UNION ALL
29.SELECT 10265,2 UNION ALL
30.SELECT 10277,2 UNION ALL
31.SELECT 10251,3 UNION ALL
32.SELECT 10253,3 UNION ALL
33.SELECT 10256,3 UNION ALL
34.SELECT 10250,4 UNION ALL
35.SELECT 10252,4 UNION ALL
36.SELECT 10248,5 UNION ALL
37.SELECT 10254,5 UNION ALL
38.SELECT 10249,6 UNION ALL
39.SELECT 10289,7 UNION ALL
40.SELECT 10303,7 UNION ALL
41.SELECT 10308,7 UNION ALL
42.SELECT 10262,8 UNION ALL
43.SELECT 10268,8 UNION ALL
44.SELECT 10276,8 UNION ALL
45.SELECT 10278,8 UNION ALL
46.SELECT 10255,9 UNION ALL
47.SELECT 10263,9
48. 
49.SELECT * FROM @ord

Rules

  1. The output should show the hierarchical relationship between the employees (as shown in the example above)
  2. The column "by_self" should show all the orders created by the employee (directly)
  3. The column "by_sub" should show the total of orders created by all the employees reporting to him/her
  4. The column "total" should show the total of "by_self" and "by_sub"
  5. The employees shoud be ordered by lastname, firstname

Notes

  1. Read the Submission Guidelines and make sure that your solution follows them.
  2. The solution should work on SQL Server 2005, 2008 or later versions
  3. Use this forum for any questions related to TSQL Challenge #19 
Last date for submitting your solutions

We will close this challenge for evaluation on 28 December 2009 Midnight GMT. All the solutions we receive till that date will be processed and the results will be announced in the format given here. However, you can continue to send us your solutions till the day we announce the evaluation results.

How to submit a solution after the results are published?

You can submit solutions for challenges even after we publish the results. However, there are a few things you should do before submitting your solutions.

  • Do a basic testing of your solution using the sample data we post along with the results of the evaluation. See an example here.
  • If your solution passes the basic testing, do a logic testing of your solution. We will publish the data to be used for the logic testing along with the challenge results. You can see an example here.
  • If your solution passes the logic testing, do a load testing of your solution using the load testing data that we publish along with the challenge results. You can see an example here.
  • After load testing, match your results with the results we have published for that challenge. (see an example here). If the results of your solution comes in the top 10 solutions listed on the results page, go ahead and send us your solution. Make sure that you send us the results of your load testing along with your submission.
  • We will re-evalute your solution and if it comes in the top 10, we will list it in the results page and you will be added to the winners page (see an example here) and will get a certain number of SQL Stars based on the grade of your solution.

Join SQL Server Challenge Idea Contest

We would like to welcome you to the SQL Server Challenge Idea Contest 2010-Q1. Submit an interesting challenge idea or details of a TSQL problem that you have seen, heard or solved. Authors of winning solutions will get a cash prize of $100 and 10 SQL Stars. Read More >>

Syntax Bookmark of the Day! – SQL Server Backup Syntax
techtips.jpg
Quick and detailed reference for SQL Server FULL BACKUP command
http://syntaxhelp.com/sqlserver/backup/full

About the Author

Alejandro is a Database developer at Bank of America.He has been working with SQL Server for almost 10 years by now, OLTP and OLAP. Lately he has been more dedicated to dimensional modeling, ETL, OLAP, and reporting services, but his passion is T-SQL. See Alejandro's Profile.

Posted: 12-14-2009 1:50 AM by Rui Carvalho | with 10 comment(s)
Filed under: ,

Comments

Ramireddy said:

Hi,

Media Gallery is not allowing to upload the solutions..

There is some issue in it.....

# December 14, 2009 1:35 PM

Jacob Sebastian said:

I doubt it is an issue with the browser you are using. In the past we had similar issues with google chrome. I would suggest you use a different browser and try again.

# December 14, 2009 10:24 PM

Ramireddy said:

Thanks Jacob,

I will use google chrome only in my home..... Anyway, I uploaded from my office, where i have only IE..

# December 14, 2009 11:00 PM

Roby Van Hoye said:

For some reason I'm unable to use 'reply' on the forum... The error thrown seems to indicate a security problem :

---

Access Denied: Reply Permission Denied

Either the forum does not exist or you do not have permissions to reply to posts within the forum.

---

I have a question though : why do you guys "insist" to have the input data in Table variables ? They kind of behave different (read : worse) than ordinary tables which is where data normally resides (eg. statistics, indexes, ...) And they make testing slow as for each test one has to declare + load the table again (from an existing table).

=> Wouldn't it be a lot easier to have an empty database with just those tables in it ? The added benefit of (potentially) having indexes on said input data might make the challenge a bit more realistic. Besides, let's agree : @emp and @order don't even have proper PK's !?!? What kind of an example is that in an advanced SQL Challenge ? =/

ps: as for the 'only one query allowed, no variables etc' - rules, I'm no fan of that either as (often) means working around limitations instead of using the full potential of the system. Then again, nobody is forcing me to take part in this =)

# December 15, 2009 6:28 AM

Jacob Sebastian said:

Hi Roby,

You need to be a member of the group 'tsql challenges' to be able to post a message in the forum. beyondrelational.com/.../default.aspx

rgds

Jacob

# December 15, 2009 6:59 AM

Erick said:

Hello,

What if a person has no orders. Should they appear in the results?

# December 17, 2009 5:39 PM

Erick said:

Found the answer in the forum

# December 17, 2009 6:03 PM

jcelko said:

This is so much easier if the organizational chart hierarchy is modeled with a Nested Sets Model and not an Adjacency List Model.

# December 22, 2009 3:20 PM

Sergejack said:

Should the solution works with million(s) of lines?

# December 23, 2009 8:04 AM

Jacob Sebastian said:

we use a large table to do a performance test of the solutions. it may not be always 1 million..sometimes less and some times more depending upon the nature of the challenge.

We will be able to decide the number of rows to test only when the evaluation starts. So I would suggest you make sure that your solution is optimized to the maximum possible so that it will return best results when testing with larger set of data.

# December 23, 2009 8:40 AM