Question : Function to implement 'round-robin' selection?

I believe an SQL function is the best way to do what I need, but I'm not sure...
I need to distribute sales leads to remote offices.  In a given zip code, there may be 0, 1, or more offices.  If a lead comes in for a particular zip code, say 11111, and there is 1 office, I send it there.  If there are zero, an administrator deals with it.  If there is more than one, I want to distribute these round-robin.  So, I have two tables:

Offices - Part of a crm system, and not updatable by us;  the relevant columns are:
Office_ID char(5)
Zip char(5)

OfficePick - Our table that we can define as we choose:
Office_ID char(5)
Distrib int

What I want to happen is this logic:
If there is more than 1 office in a given zip code from offices
   if any of these offices are not in OfficePick already, insert them with a distrib value of 0
   select the one of the offices from the first 'if' that has the lowest distrib value
      in the case of a tie, pick one randomly (could be rowid), doesn't really matter
      increment the selected office's distrib value by 1

Any suggestions on the best way to implement this?

Answer : Function to implement 'round-robin' selection?

Correction on the:


SELECT Zip, MAX(Offices.Office_ID ) Office_ID
INTO #YOURPIK
FROM Offices
INNER JOIN OfficePick
ON Offices.Office_ID = OfficePick.Office_ID
WHERE EXISTS (
SELECT 1 FROM (
SELECT Zip, Offices.Office_ID, MIN(Distrib) MINDistrib
FROM Offices
INNER JOIN OfficePick
ON Offices.Office_ID = OfficePick.Office_ID
GROUP BY Zip, Offices.Office_ID
) T
WHERE Offices.Zip = T.Zip AND Offices.Office_ID = OfficePick.Office_ID AND MINDistrib = OfficePick.Distrib

)
GROUP BY Zip

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
---- if any of these offices are not in OfficePick already, insert them with a distrib value of 0
INSERT INTO OfficePick
SELECT Office_ID, 0 
FROM Offices
WHERE NOT EXISTS (
		SELECT 1
		FROM OfficePick 
		WHERE  Offices.Office_ID = OfficePick.Office_ID 
)
 
--If there is more than 1 office in a given zip code from offices ONE OFFICE ID PER ZIP with the less Distrib
 
SELECT Zip, MAX(Offices.Office_ID ) Office_ID
INTO #YOURPIK
FROM Offices
INNER JOIN  OfficePick 
	ON  Offices.Office_ID = OfficePick.Office_ID
WHERE EXISTS   (
		SELECT 1 FROM (
				SELECT  Zip, Offices.Office_ID, MIN(Distrib) MINDistrib
				FROM Offices 
				INNER JOIN  OfficePick 
				ON  Offices.Office_ID = OfficePick.Office_ID
				GROUP BY Zip, Offices.Office_ID 
		) T
		WHERE  Offices.Zip = T.Zip AND Offices.Office_ID = OfficePick.Office_ID AND MINDistrib = OfficePick.Distrib
 
	)
GROUP BY Zip
	 
---update the picked office with Distrib+1	 
UPDATE T
SET Distrib = Distrib+1
FROM OfficePick T
INNER JOIN #YOURPIK
ON  #YOURPIK.Office_ID = T.Office_ID
Open in New Window Select All
Random Solutions  
 
programming4us programming4us