The easiest and fastest way to create ad hoc reports from SQL Server
Got a SQL Server or .NET question? Discuss it in the forums. (SQL Server Forums | Dot NET Forums)
First Time? You can support us by signing up. It takes only 5 seconds. Click here to sign up. If you already have an account, click here to login.

TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Who among us wouldn't want to go back to our childhood and enjoy those lovely playful time once again? Well, here is a challenge that might take you back to your childhood and might keep you busy sorting and filling colorful balls into different boxes. Here is an interesting challenge submitted by our new contributor RamiReddy.

What is new with TSQL Challenges

As I have mentioned a few times in the past, we are working very hard on improving 'TSQL Challenges' and a number of people from the SQL Server community have been helping us to come up with some improvements.

Allowing multi-statement solutions

We were getting a large number of comments against the 'all-in-one-query' requirement that we put on the challenges. They argue that not all real-world problems are solved with the 'single-query' approach. There are also times when a 'multi-step' query performs better than a 'single-query' approach. They are right.

On the other side, we do get a lot of feedback from people who say that they like the 'one-query' requirement because that is the real 'fun' in these challenges. The 'single-query' requirment makes them think beyond the regular problem solving methods and they find it very interesting. They are right too.

We are still working on setting up a plan that makes both the groups happy. Till then we will allow 'multi-statement' solutions selectively. It means that some challenges will allow multi-statement solutions and some will not. If the challenge allows multi-statement solutions, we will specifically mention it along with the challenge description.

Early Challenge Review

To improve the quality of the challenges and the clarity of the rules of the challenges, we started inviting volunteers to do an 'early challenge review' where they get a chance to review the challenge description and rules and give us some suggestions to improve the quality of the challenges. I am very glad that a few people already came forward to help us and if any of you would like to volunteer, please contact me privately.

Physical Tables instead of memory tables

Starting with this challenge, we will be providing sample data in physical tables instead of table variables. Your solution should not include the code to populate the sample tables. You can assume that the sample tables with data exist in the current database.

Challenge Moderator

Starting with this challenge, we are also introducing a 'Challenge Moderator'. The moderator of a challenge will be helping you with your questions in the forums and everything else that you would need related to a certain challenge. RamiReddy is the Moderator for this challenge and he will be available to help you with any questions related to this challenge.

The Challenge

We have got some boxes and balls. Our job is to put balls into those boxes. But, wait a second! The balls should be filled into the boxes based on some rules and preferences configured by the user. Here are the rules.

  • A box can have only one ball
  • A ball can be placed only in one box
  • Number of balls and number of boxes will always be the same.
  • All boxes should be filled and all balls should be used
  • There will be a configuration table where the preferences of the user will be stored. The preference setting should be followed when putting a ball into a box.

In addition to this, there will be a configuration table where the preferences of the user will be stored. The preference setting should be followed when putting a ball into a box.

Sample Data

Here is the sample data for this challenge.

Table: TC22_Boxes

This is the table that stores the boxes. Each row in this table represents a box. Boxes in this table will always be unique.

BoxId       BoxName
----------- --------------------
1           Box 1
2           Box 2
3           Box 3
4           Box 4
5           Box 5
6           Box 6

Table: TC22_Balls

This table stores the balls. Each row in this table represents a ball. Balls in this table will always be unique.

BallId      BallName
----------- --------------------
1           Ball 1
2           Ball 2
3           Ball 3
4           Ball 4
5           Ball 5
6           Ball 6

Table: TC22_Preferences

This table stores the preferences set by the user. There may be multiple preferences configured for each box or ball. For example, the second and third rows indicate that you can put ball #1 or ball #3 into box #2. You can take any one of the preferences but need to make sure that all boxes will be filled and all balls will be used.

PreferenceId BoxId       BallId
------------ ----------- -----------
1            1           1
2            2           1
3            2           3
4            3           2
5            3           3
6            4           1
7            4           2
8            4           3
9            4           4
10           4           5
11           4           6
12           5           4
13           5           5
14           6           5
Expected Results

Here is the expected results based on the above sample data.

Box         Ball      
----------- ----------- 
Box 1       Ball 1           
Box 2       Ball 3           
Box 3       Ball 2           
Box 4       Ball 6           
Box 5       Ball 4           
Box 6       Ball 5           
Sample Scripts

User the following scripts to generate the sample data for this challenge

-- --------------------------------------------------
-- Create the 'Boxes' table
-- --------------------------------------------------
IF OBJECT_ID('TC22_Boxes','U') IS NOT NULL 
BEGIN
	DROP TABLE TC22_Boxes
END
GO

CREATE TABLE TC22_Boxes
(
    BoxId INT IDENTITY PRIMARY KEY,
    BoxName VARCHAR(20)
)
GO

INSERT INTO TC22_Boxes (BoxName)
SELECT 'Box 1' UNION all
SELECT 'Box 2' UNION all
SELECT 'Box 3' UNION all
SELECT 'Box 4' UNION all
SELECT 'Box 5' UNION all
SELECT 'Box 6' 


-- --------------------------------------------------
-- Create the 'Balls' table
-- --------------------------------------------------
IF OBJECT_ID('TC22_Balls','U') IS NOT NULL 
BEGIN
	DROP TABLE TC22_Balls
END
GO

CREATE TABLE TC22_Balls(
    BallId INT IDENTITY PRIMARY KEY,
    BallName VARCHAR(20)
)
GO

INSERT INTO TC22_Balls (BallName)
SELECT 'Ball 1' UNION all
SELECT 'Ball 2' UNION all
SELECT 'Ball 3' UNION all
SELECT 'Ball 4' UNION all
SELECT 'Ball 5' UNION all
SELECT 'Ball 6' 

-- --------------------------------------------------
-- Create the 'Preferences' table
-- --------------------------------------------------
IF OBJECT_ID('TC22_Preferences','U') IS NOT NULL 
BEGIN
	DROP TABLE TC22_Preferences
END
GO

CREATE TABLE TC22_Preferences(
    PreferenceId INT IDENTITY PRIMARY KEY,
    BoxId INT,
    BallId INT
)
GO

INSERT INTO TC22_Preferences (BoxID, BallID) 
SELECT 1,1 UNION all
SELECT 2,1 UNION all
SELECT 2,3 UNION all
SELECT 3,2 UNION all
SELECT 3,3 UNION all
SELECT 4,1 UNION all
SELECT 4,2 UNION all
SELECT 4,3 UNION all
SELECT 4,4 UNION all
SELECT 4,5 UNION all
SELECT 4,6 UNION all
SELECT 5,4 UNION all
SELECT 5,5 UNION all
SELECT 6,5

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 #22 

Submitting Multi-statement solutions

Unlike the previous challenges, this one allows multi-statement solutions. Your solution does not need to be a single-query solution. You can use RBAR, cursors, loops etc in your solution. However, we need to apply some restrictions on your code so that your solution can be evaluated using our automated evaluation script.

Your code should not create objects like views, functions or stored procedures. Your solution should be a single batch. There should not be any 'GO' statements between your solution. We will put the entire content of your solution to the body of a stored procedure and if we do that, your code should not produce an error. For example, you need to make sure that the following works:

CREATE PROCEDURE TC_Eval
AS
BEGIN
SET NOCOUNT ON
-- your code here
END
GO

Your code should not include the code to create the sample data. You can assume that the sample tables already exist in the current database.

Last date for submitting your solutions

We will close this challenge for evaluation on 8 February 2010 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.

FAQ
  1. Are Boxid, BallID and PreferenceId  sequential with no gaps ?
    • The column is an identity column and identity columns are not expected to be sequential. There can be gaps/missing-ids.
  2. Is there a maximum number of balls and boxes?
    • No, there is no maximum number of balls and boxes. The number of balls and boxes will always be the same so that if you fill the boxes correctly, all boxes will be filled and all balls will be used.
  3. What sort order is the final result set ?
    • Sort the output by Box ID
  4. Is there any priority order if there are 2 Balls going into 1 box ?
    • No, there is no priority order, because there is only one ‘correct’ box for each ball.
  5. Will there be a case in which two balls are preferenced only to one box? For example, can ball3 and ball5 be referenced only to box7 ?
    • No, two balls can't be preferenced ONLY to one box. It can happen that ball 3 and 5 are referenced to box 7. But in such a case, either or both of them will also have another preference to another box.
  6. Is it guaranteed that the sample data have one and only one valid solution?
    • Yes, There will be only on ‘correct’ solution for a given set of sample data. If you assign a ball to an incorrect box, you will end up with another box that does not have any ball to fill in.
  7. Can we create indexes on the sample tables?
    • No, No modifications should be done to the sample tables.
  8. Can I create and use a tally/number table in my queries?
    • No, you are not allowed to create and use your own tally tables. However if you need a tally table, you can use the script given here to create a tally table. When you send us your solution, do not include the script to create the tally table. Your query can assume that the tally table already exists on the database where we will run your queries.
  9. Can I use a CLR procedure/function
    • No, CLR code is not allowed.
Early Review Team

The Early Review team did a great job by reviewing the challenge description, rules and helped to compile the FAQ list. We have made the required updates to the challenge based on the recommendations of the Early Review Team.

About the Author

Challenge Idea by


Challenge Evaluation Details

Evaluation QueueAll SubmissionsAccepted Submissions
Basic Testing ResultsLogic Testing ResultsPerformance Testing Comparision
Winners

Though the evaluation of this TSQL Challenge is completed and winners are announced, you can still submit a solution and we will be very happy to review it. Before submitting, make sure that your solution passes the basic testing and logic testing and the performance statics are good. See the submission guidelines before submitting your solution.

Previous Challenge

Current Challenge

Next Challenge

TSQL Challenge 21 - Reading, recognizing and processing graphical representation of digits.TSQL Challenge 37 - Calculate the downtime and duration of servers based on the monitoring logTSQL Challenge 23 - Calculate the uptime and downtime of a system by reading the data from an audit log

Share

Comments

# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Monday, January 25, 2010 11:50 AM by Mike Lewis

Will there always be a record in the preferences table for every box and every ball?


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Monday, January 25, 2010 12:55 PM by Ramireddy

Yes, There will be atleast one Preference for every box and ball...


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Tuesday, January 26, 2010 2:10 AM by Pragnesh Patel

As this challenge is Multi-statement solutions, can we create a physical/#table to derive output results.


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Tuesday, January 26, 2010 6:23 AM by Jacob Sebastian

Yes, you can create #temp tables or table variables in this solution.


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Wednesday, January 27, 2010 7:18 PM by Jesse Roberge

Hey I came up with a result that fits the preference table that is different from your 'expected result' but you said there is only supposed to be one correct solution.   Did I miss a rule?

Box Ball

Box 1 Ball 1

Box 3 Ball 2

Box 2 Ball 3

Box 5 Ball 4

Box 6 Ball 5

Box 4 Ball 6


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Wednesday, January 27, 2010 7:31 PM by Jesse Roberge

Here is an expanded view in the alternate match (with PreferenceIDs).

BoxID Box BallID Ball PreferenceID

1 Box 1 1 Ball 1 1

3 Box 3 2 Ball 2 4

2 Box 2 3 Ball 3 3

5 Box 5 4 Ball 4 12

6 Box 6 5 Ball 5 14

4 Box 4 6 Ball 6 11


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Wednesday, January 27, 2010 9:15 PM by Jesse Roberge

Oh duh!  The sort order didn't match.  The expected results are sorted by box but I sorted by Ball ID and got my boxes and balls mixed up.  Well that means it works!  I'm going to get it to work with a cartesian product preferences table now.


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Thursday, January 28, 2010 8:05 AM by Bhavani

can we use the while loop to get the solution.


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Thursday, January 28, 2010 8:13 AM by Jacob Sebastian

Yes. While loops are allowed in this challenge.


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Thursday, January 28, 2010 10:16 AM by karinloos

As there is only 1 correct ball for a box and thus only 1 correct solution, can we assume that there will be no logic testing for "funny data"..

Ie if you have a working solution on the given sample set, it will thus work on all sets as the only difference can be in the size of the set?


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Thursday, January 28, 2010 11:20 AM by Jacob Sebastian

@karinloos,

your assumption is right. The tricky testing will be done with more data, but it will certainly follow the rules given in the challenge. There will be only one correct solution.


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Thursday, January 28, 2010 10:03 PM by sreedharange

I've got the solution, but now how do I submit it?  Maybe it is obvious to others, but I am new to this site (joined today); finding the solution was much easier than finding out how to submit my solution :)


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Friday, January 29, 2010 12:27 AM by Jacob Sebastian

@sreedharange,

It looks like you did not pay attention to the 'notes' section. Take a look at the 'submission guidelines' page where you can get clear instructions on how to submit your solution.

beyondrelational.com/.../tsql-challenges-terms-and-conditions-submission-guidelines-evaluation-process-and-faq.aspx


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Friday, January 29, 2010 9:19 AM by dishdy

In question 8 above you state that you cannot create your own tally table.

1. Why not?

2. Is this something new starting with this challeng or has this always been the rule?


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Friday, January 29, 2010 9:35 AM by Jacob Sebastian

@dishdy,

Tally table was never allowed, except for master..spt_values which has only a limited number of rows.

Recently we made a tally table available that you can use in your solutions. The script for this tally table is given at databasechallenges.com/.../tally-table

This tally table will be present in the database that we use for evaluating your solutions. So if you want to use a tally table, use only this script.


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Friday, January 29, 2010 10:21 AM by dishdy

Jacob,

So you are saying a sub-query in your solution with a series of cross-joins to generate a tally table 'on the fly' is NOT permitted?

Or are you saying that you cannot generate a physical table (temporary or not) that acts as a tally table?


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Friday, January 29, 2010 10:47 AM by Jacob Sebastian

@dishdy,

I was refering to physical tables.

You can build your own tally table on-the-fly if you wish to do so.


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Friday, January 29, 2010 10:49 AM by Jacob Sebastian

Again, since this challenge allows multi-statement queries, loops etc, you are also permitted to use table variables or #temp tables.

(this is specifically for this challenge).

However, make sure that we will be able to embed your code within the body of a stored procedure (as explained in the description)


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Monday, February 01, 2010 2:19 PM by SparkS

I got an error when running the stored procedure creating script:

Msg 102, Level 15, State 1, Procedure TC_Eval, Line 7

Incorrect syntax near ';'.

If I remove the ';' after GO, it works.

Did I miss something. Thanks.


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Monday, February 01, 2010 2:50 PM by Brad Schulz

That should be changed.

GO is not an actual T-SQL command... it's just a batch-end indicator/separator.  It should never have a semi-colon after it.

Jacob or Ramireddy, can you change that and get rid of the semicolon?


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Monday, February 01, 2010 9:33 PM by Jacob Sebastian

Corrected the typo.

Thanks for pointing it out.


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Tuesday, February 02, 2010 2:19 AM by dishdy

Jacob,

The 'Read More' links for 22 links to 21.


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Tuesday, February 02, 2010 2:30 AM by Jacob Sebastian

corrected!

thanks


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Wednesday, February 17, 2010 10:42 AM by Len Binns

When will the results be posted?


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Wednesday, February 17, 2010 11:59 AM by Jacob Sebastian

@Len,

I think it will be another 2-3 weeks. We are clearing the backlogs currently.


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Tuesday, June 08, 2010 10:06 AM by Sergejack

tsqlc_Tally?

Where is it?


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Tuesday, June 08, 2010 10:31 AM by Jacob Sebastian

# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Friday, June 11, 2010 10:18 AM by Sergejack

Solutions cannot be seen (Page Requests fail).


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Friday, June 11, 2010 10:25 AM by Jacob Sebastian

is there a specific page that fails? can you post the URL?


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Friday, June 11, 2010 10:32 AM by Jacob Sebastian

Ok guys, found that there is a technical glitch. The solutions are not visible yet. It is going to take some time to fix that. this will be available by monday morning.


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Friday, June 11, 2010 10:34 AM by Jacob Sebastian

wait a second..looks like a URL problem. Let me correct it.


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Friday, June 11, 2010 10:43 AM by Jacob Sebastian

OK, it is fixed. Does it look good now?


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Wednesday, June 16, 2010 7:14 AM by Sergejack

It does.


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Thursday, June 17, 2010 9:13 AM by Pragnesh Patel

Hi Jacob,

I am very much confused by the winners list for this challenge....

I tried to execute the couple of solutions from winner list with Load testing data provided and here is the list of what each solutions take time to executive.

Solution -----------> Execution Time

Top winner ( carlos benito ) --------> 1.44 minutes

Runner Up ( Jesse Roberge ) -----> 1.23 minutes

...

...

2nd Last winner ( jmc bkk  ) -------------> 0.01 Minutes

Last winner ( Michael Lewis  ) -------------> 0.00 Minutes

Can you please help me out what criteria applies to identify the winners.

-Pragnesh


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Thursday, June 17, 2010 9:34 AM by Jacob Sebastian

@Pragnesh,

The winners are identified based on the read, write, CPU, duration rank as per given on databasechallenges.com/.../load_testing_results. Each solution is executed 5 times and the average of the stats is collected. You can click on the hyper link given on the stats page to see the execution statistics of each of the 5 runs.


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Thursday, June 17, 2010 10:29 AM by Pragnesh Patel

Jacob,

I understand with read, write, CPU, duration rank.

But you can see the execution time difference... its a very huge.

In real world scenario any query takes 1.44 minutes to execution is always not acceptable by anyone.

I am still not clear with the weightage given to read, write, CPU, duration rank.


# re: TSQL Challenge 22 - Filling balls into boxes based on rules and preferences

Thursday, June 17, 2010 12:47 PM by Jacob Sebastian

@Pragnesh,

You are refering to the execution time the solution took on your computer. I have no idea why it takes on your side. We run all the solutions in similar environment and the results are captured. Take a look at our stats and you will realize that the solutions are correctly ranked.

We periodically re-run the load testing. So let us wait for the next load testing and see if the statistics will change or not.

rgds

Jacob


Copyright © Beyondrelational.com