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
I would use a conversion table and put in all combinations. So even if 5000g ->5kg -> 1 box, I would put gram -> box conversions as well. Something like this:
create table unit_unit_conv(
from_unit varchar(10) not null
,to_unit varchar(10) not null
,rate decimal(10,6) not null
,primary key(from_unit, to_unit)
);
insert into unit_unit_conv values('kilogram', 'kilogram', 1);
insert into unit_unit_conv values('kilogram', 'gram', 1000);
insert into unit_unit_conv values('kilogram', 'box', 0.2);
insert into unit_unit_conv values('gram', 'gram', 1);
insert into unit_unit_conv values('gram', 'kilogram', 0.001);
insert into unit_unit_conv values('gram', 'box', 0.0002);
insert into unit_unit_conv values('box', 'box', 1);
insert into unit_unit_conv values('box', 'kilogram', 5);
insert into unit_unit_conv values('box', 'gram', 5000);
So whatever unit of measure you have, you can convert it into any unit by multiplying the quantity you have with the rate column in this table. So if you have a table of items like this:
create table items(
item_id varchar(10) not null
,item_qty int not null
,item_qty_unit varchar(10)
);
insert into items values('chicken', 5, 'kilogram');
insert into items values('babies', 5000, 'gram');
insert into items values('beef', 1, 'box');
...and you want to convert everything to boxes, you would query the data like this:
select i.item_id
,i.item_qty as qty_original
,item_qty_unit as qty_unit_original
,i.item_qty * c.rate as box_qty
from items i
join unit_unit_conv c on(i.item_qty_unit = c.from_unit)
where c.to_unit = 'box';
+---------+--------------+-------------------+----------+
| item_id | qty_original | qty_unit_original | box_qty |
+---------+--------------+-------------------+----------+
| chicken | 5 | kilogram | 1.000000 |
| babies | 5000 | gram | 1.000000 |
| beef | 1 | box | 1.000000 |
+---------+--------------+-------------------+----------+