重新分配逻辑

时间:2017-10-04 21:41:24

标签: python sql logic

我正在尝试查看是否可以在SQL中实现重新分配逻辑,请告诉我这是否可以在SQL中使用或指向正确的位置。

表1:

Store   Employee    Customer
1             A        1
1             A        2
1             B        3

每家商店的客户数量是随机分布的,有些员工可能有30位客户,有些则可能低至1位。

我试图了解每个商店内是否可以在员工中重新分配客户

例如:

Employee A has 30 customers
Employee B has 9 Customers
Employee C has 2 customers

我想重新分配到以下内容: 每名员工最低为10

Employee A has 21 customers
Employee B has 10 customers
Employee C has 10 Customers

感谢

2 个答案:

答案 0 :(得分:0)

请在下面找到我的解决方案。用于IIF的SQLServer 2012+否则使用CASE

declare @mytable table (employee varchar(10), customers int)
declare @min smallint = 10
declare @divcustomers smallint 
declare @totalcustomers smallint 
declare @balance smallint 

insert into @mytable
values ('A',   18),
('B',       23),
('C',       13),
('D',       15)

-- get even allocation
select @divcustomers = sum(customers)/count(employee), @totalcustomers = sum(customers) from @mytable

-- re-initialise minimum otheriwse get the allocation
select employee, iif(customers< @min and @divcustomers > @min-1,@min,@divcustomers) customers
into #temptable
from @mytable t

-- update the balance to the most number of customers.. keeping the least to the minimum
update #temptable 
set customers = customers + (select @totalcustomers - sum(customers) from #temptable)
where employee = (
select top 1 employee from @mytable
order by customers desc

)

select * from #temptable

drop table #temptable

答案 1 :(得分:0)

这是一个完全忽略起始位置的解决方案。如果唯一的标准是平衡客户与员工,我们关心的是员工在哪个商店,哪个客户在哪个商店,以及均匀分配。即使是10个限制似乎也不是特别相关。如果我们均衡地平衡客户,要么有足够的客户给每个员工10个或者没有(在这种情况下,任何其他方法也会失败)。

我假设每家商店的客户数量至少与员工一样多,同一客户不能分配给同一家商店的多名员工。

这是SQL服务器版本(sqlfiddle):

update tab 
SET tab.employee = thedata.employee
FROM 
(SELECT storeemp.store, storeemp.employee, storecus.customer
FROM
(SELECT store, customer, row_number() over (partition by store order by customer) as r
FROM tab
GROUP BY store, customer) storecus
join
(SELECT store, employee, row_number() over (partition by store order by employee) as r
FROM tab
GROUP BY store, employee) storeemp
on storecus.store = storeemp.store and (storecus.r-1)%(SELECT count(distinct employee) from tab where tab.store=storecus.store) = storeemp.r-1) theta
WHERE tab.store = thedata.store and tab.customer = thedata.customer

这是Oracle版本(MOD而不是%):

update tab 
SET tab.employee = thedata.employee
FROM 
(SELECT storeemp.store, storeemp.employee, storecus.customer
FROM
 (SELECT store, customer, row_number() over (partition by store order by customer) as r
 FROM tab
 GROUP BY store, customer) storecus
join
 (SELECT store, employee, row_number() over (partition by store order by employee) as r
 FROM tab
 GROUP BY store, employee) storeemp
on 
 storecus.store = storeemp.store 
 and mod(storecus.r-1,(SELECT count(distinct employee) from tab where tab.store=storecus.store)) = storeemp.r-1) thedata
WHERE tab.store = thedata.store and tab.customer = thedata.customer