I am looking for a solution for a custom unit conversion in SQL, the database my company used is Microsoft SQL server, I need to write a SQL to return a conversion factor based
Now that's a tricky one. It looks like you are going to need a recursive-select, or a cursor to solve it. Basically, what you want to do is select from the unit conversion table where itemid = @desiredId and vendorid = @desiredVendor and unit2id = @finalUnitId. Then, you will want to run the same query, but where unit2id = unit1id from the query you just ran -- until unit1id = @originalUnitId. All the while, keeping a running conversion-factor.
So, begin with something like this:
declare @factor float
set @factor = 0
select unit1id, quantity1, quantity2 from unitconversion where itemid = 1001 and vendorid = 5000 and unit2id = 305
set @factor = @factor + quantity1 / quantity 2
Then, you will want to check to see if unit1id
selected from the above equals the unit you want to end up with (in you example, you are checking to see if unit1id = 10). If not, run the same query again, but restrict for a unit2id of 10.
This is just a rough outline of how I would do it. There are a few assumptions made here, mainly that if you follow the chain of units that the previous unit is always smaller than the unit you are testing for, but I think this may be enough to convey the gist of it. This will probably work out best implemented as a UDF that returns the factor based on the product, vendor, start, and end units. I would use a while
statement.