Средняя себестоимость единицы по каналам
SQL, по которому посчитано
WITH period AS (
SELECT date_trunc('month', max(date)) AS month_start
FROM sales
)
SELECT
channel,
round(sum(cost_of_goods) / nullif(sum(units), 0), 2) AS avg_cost_per_unit
FROM sales
WHERE date >= (SELECT month_start FROM period)
AND date < (SELECT month_start + INTERVAL 1 MONTH FROM period)
GROUP BY channel
ORDER BY avg_cost_per_unit DESC