최적화 문제다. 유사도 개념을 이용하여 시뮬레이션 하면 쉽게 최적화 할 수 있다.
--데이터 만들기
;with temp(오더번호, 규격, 오더길이, 만들개수)
as
(
select 'A', 2, 100, 10 union all
select 'B', 1, 30 , 1 union all
select 'C', 1, 40 , 4 union all
select 'D', 3, 80 , 6 union all
select 'E', 1, 50 , 7 union all
select 'F', 3, 100, 15
)
select * into #temp
from temp
select N'홍길동' name into #worker union all
select N'강감찬' union all
select N'이순신'
--simulation
--similarity, euclidean distance
set nocount on
if object_id('tempdb.dbo.#result') is not null
drop table #result
create table #result(
오더번호 nvarchar(200)
, 규격 int
, 오더길이 int
, 만들개수 int
, 작업자 nvarchar(200)
)
declare
@i int
, @dist float
, @min_dist float
set @i = 1
while(@i <= 100)
begin
if object_id('tempdb.dbo.#rand') is not null
drop table #rand
select
a.오더번호
, a.규격
, a.오더길이
, a.만들개수
, b.작업자
, b.num
into #rand
from (select *, row_number() over(order by newid()) - 1 num from #temp) a
inner join (
select
name 작업자
, row_number() over(order by newid()) - 1 num
, count(*) over() cnt
from #worker
) b
on a.num % b.cnt = b.num
declare
@v1 float
, @v2 float
, @v3 float
select
@v1 = sum(규격)
, @v2 = sum(오더길이)
, @v3 = sum(만들개수)
from #rand
where num = 0
select @dist = sqrt(sum(n))
from (
select
power(@v1 - sum(규격), 2) + power(@v2 - sum(오더길이), 2) + power(@v3 - sum(만들개수), 2) n
from #rand
where num <> 0
group by
num
) t
if @i = 1
begin
insert #result
select
오더번호
, 규격
, 오더길이
, 만들개수
, 작업자
from #rand
set @min_dist = @dist
end else
begin
if @min_dist > @dist
begin
truncate table #result
insert #result
select
오더번호
, 규격
, 오더길이
, 만들개수
, 작업자
from #rand
set @min_dist = @dist
end
end
--print @i
set @i = @i + 1
end
print @min_dist
select
오더번호
, 규격
, 오더길이 * 1.0 / 만들개수 [오더길이/만들개수]
, 작업자
from #result
order by 작업자