您的案件分佈並不算太差。我建議以下方法:
(1)獨立的客戶分爲兩組。 。 。多個案例和單個案例。
(2)指定的多個箱子的情況下工人在一個循環的方式。
(3)將個案分配給個案工作者以平衡每個個案工作者。
這將適用於您的特定分佈(大多數是單身人士)。它不一定是通用算法。
這裏是SQL:
with multiples as (
select CustomerId, COUNT(*) CaseCnt,
ROW_NUMBER() over (partition by CustomerId order by CustomerId) % @NumHandlers as theHandler
from customers c
group by CustomerId
having COUNT(*) > 1
),
h as (
select theHandler, SUM(CaseCnt) as CaseCnt,
SUM(CaseCnt) - (NumCusts/@NumHandlers) as StillNeeded
from multiples cross join
(select COUNT(*) as NumCusts from customers c) const
group by theHandler
),
hsum as (
select h.*, SUM(StillNeeded) over (order by StillNeeded) as endnum,
SUM(StillNeeded) over (order by StillNeeded) - StillNeeded + 1 as startnum
from h
),
singles as (
select CustomerId, ROW_NUMBER() over (partition by CustomerId order by CustomerId) as seqnum
from Customers
group by CustomerId
having COUNT(*) = 1
),
singlesh as (
select singles.Customerid, h.theHandler
from singles join
hsum
on singles.seqnum between h.startnum and h.endnum
)
select *
from ((select CustomerId, theHandler
from multiples
) union all
(select CustomerId, theHandler
from singlesh
)
) t
的SQL幾乎遵循上面的說明。它首先以循環方式隨機分配多個記錄給處理程序。處理程序只是從0到@NumHandlers的數字。然後計算「StillNeeded」情況的數量以達到最大值。注意:這假定處理程序的數量是客戶數量的確切倍數。修正這個問題使查詢看起來更加複雜。
然後它會計算每個處理程序仍需填寫的數量。關鍵是將其作爲累積和(這使用SQL Server 2012語法,在早期版本中,您使用相關子查詢執行此操作)。這個信息然後被用來將單例分配給每個處理程序。
最後一步是union
這兩組客戶在一起,倍數和單身。
我想你想要的是NTILE。你可以谷歌它,或看看這裏http://stackoverflow.com/questions/14355324/want-to-learn-more-on-ntile – Randy