I’ve encountered similar challenges with weighted averages in SQL. Here’s an approach that might work for you:
SELECT
product_id,
product_name,
SUM(unit_cost * stock_qty) / SUM(stock_qty) AS avg_cost,
SUM(stock_qty) AS total_qty,
SUM(unit_cost * stock_qty) AS total_value
FROM products
INNER JOIN inventory ON product_id = inventory_id
WHERE product_type = ‘FG’ AND stock_qty != 0
GROUP BY product_id, product_name
This query calculates the weighted average cost, total quantity, and total value for each product. The GROUP BY clause ensures you get results per product. Remember to test and adjust based on your specific database structure and requirements.
yo max, have u tried using subqueries? might help u break it down. something like:
SELECT p.product_id, p.product_name,
(SELECT SUM(unit_cost*stock_qty)/SUM(stock_qty) FROM inventory WHERE inventory_id=p.product_id) AS avg_cost
FROM products p
WHERE p.product_type=‘FG’
hey there! have you tried using window functions? they’re super handy for this kinda stuff. maybe something like SUM(unit_cost * stock_qty) OVER (PARTITION BY product_id) could work? just brainstorming here. what other approaches have u considered? curious to hear your thoughts!