Complex SQL working for inventory data