on ‎2014 Apr 20 5:20 AM
I have a good working sql that works in sql server. The logical computation calculates how many lengths will fit a barrel. Maximum capacity per drum is 14300 meters. My question is how I can get this to work with Sybase.
Declare @tblLength table (num int, qty int, unit varchar(20))
insert @tblLength
values
(2,2500,''),
(1,3800,''),
(1,4200,''),
(1,6500,''),
(1,8300,'')
;with cte as
(
select i=1, qty, unit from @tblLength where num >= 1
union all
select i=i+1, t.qty, t.unit from @tblLength t, cte where t.qty=cte.qty and t.unit = cte.unit and t.num >= i+1
),
cte2 as
(
select *, id=row_number() over (order by qty desc) from cte
),
cte3 as
(
select j=1, qty, unit, id, tot=qty, drum=1 from cte2 where id = 1
union all
select j=j+1, cte2.qty, cte2.unit, cte2.id,
tot=case when cte3.tot+cte2.qty > 14300 then cte2.qty else cte3.tot+cte2.qty end,
drum=case when cte3.tot+cte2.qty > 14300 then cte3.drum + 1 else cte3.drum end
from cte2,cte3 where cte2.id = j+1
)
select drum, qty, unit from cte3
Request clarification before answering.
For those who are algorithmically inclined ... This appears to me as being the SQL approximation of the one-dimensional "First Fit" heuristic algorithm. {a heuristic for a family of N-P complete problems related to the "Bin Packing problem"} As such, without some sort or recursion or look ahead ... it may take some time to find a simplified algorithm to make this happen.
The original solution is a creative utilization of SQL Server features. A similarly crafty SQL Anywhere solution may take a bit of effort.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
> nobody will understand what's going on there
Always a danger... whenever I code recursive unions the "nobody will understand" includes ME, five minutes later 🙂
| User | Count |
|---|---|
| 15 | |
| 9 | |
| 6 | |
| 4 | |
| 4 | |
| 4 | |
| 3 | |
| 2 | |
| 2 | |
| 2 |
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.