Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
In SQL Server 2008R2 I would like to write T-SQL code to assign account to agents based on area.

Table one is a list of accounts that has a column GroupNum by area,
HTML
Area - GROUPNUM - Account
A - 1 - 1
A - 1 - 2
A - 2 - 3
A - 2 - 4
A - 3 - 5
B - 4 - 6
B - 4 - 7
B - 5 - 8
(many more per Area/Group)
table two is a list of agent per area.
Area - Agent
A - John
A - Jane
A - Jack
B - Bill
B - Babs

I can assign the accounts randomly (using the ORDER BY NEWID() command) but the problem is I want all of one GROUPNUM to go to only one agent. Thus John would get all Area A GRoupNUM 1 and Jane would get all Area A GroupNum 2.

Now to complicate the problem I want to try and evenly distribute the accounts. So if there are 90 Area A accounts the each agent would get 30. However if I assign John account 1 the he should get account 2. He now has two of the 30.

Does this make sense?

I know this should be easy but I am having trouble.

If you could point me in a direction I would be grateful.
Thanks
Posted
Updated 3-Feb-12 5:14am
v2

For what I was looking for I sorted the table by Area/Group before assigning to an Agent. I then assigned the required number of accounts after which I check if the last assigned had related ones. This gives me what I need because there will not be a large number of related accounts, and the few extra the agent gets does not matter.
 
Share this answer
 
v2
Use Row_Number() function for having a GroupNum assigned to an agent.
See here[^]
 
Share this answer
 
Comments
Corporal Agarn 3-Feb-12 12:52pm    
Thank you for the reply. Not quite what I was looking for. But will help with another problem.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900