I want to obtain from each product the average price of the last month that each product was sold. A problem is generated in the second temporary table "price_avg" because when you change the calculation from avg (punitdolar) to price_ultimoUSD (sum (i.quantity * i.punitdolar) / sum (i.quantity)) as price_ultimateUSD to execute the query I get
"Msg 8134, Level 16, State 1, Line 64 Divide by zero error encountered. "
Try to fix it with a quantity > 0 so that it does not take negative amounts or 0 but the issue is that in doing so it stops recognizing last date and averages all the products with the same code.
Possible solution in this:
(sum(i.cantidad*i.punitdolar)/sum(i.cantidad)) as precio_ultimoUSD
go some kind of conditional that says that if the amount that divides is zero put 0 and no error
with fecha_ultima as (select itemnumber,
max(format(fecha, 'yyyyMM')) as Fecha_ultim from [gpper].[dbo].[peru_sales_report]
group by itemnumber)
--Vinculo de ultima fecha y precio promedio
,precio_avg as (
select u.itemnumber,
u.fecha_ultim,
(sum(i.cantidad*i.punitdolar)/sum(i.cantidad)) as precio_ultimoUSD
--avg(punitdolar) as precio_ultimoUSD
from [gpper].[dbo].[peru_sales_report] i
left join fecha_ultima u
on i.itemnumber = u.itemnumber and format(i.fecha, 'yyyyMM') = u.fecha_ultim where i.cantidad <> 0
group by u.itemnumber, u.fecha_ultim) --Join con tabla precios
,precioabc as (
select a.*,
b.precio_ultimoUSD from [dbo].[Precio_Inyeccion_soplado] a
left join precio_avg b
on (a.id_producto = b.itemnumber)) --Join final con v_producción_altas
select a.*,
a.peso_real_op/1000 as toneladas,
c.virgen_rec,
b.pesokilos as peso_unitario,
c.precio_teoricoUSD,
f.precio_ultimoUSD,
(costo_kardex/cantidad/3.24) as costo_unitarioUSD,
f.precio_ultimoUSD*a.cantidad as ingresoUSD,
f.precio_ultimoUSD*a.cantidad-costo_kardex/3.24 as margenUSD from [GESTION].[prod].[v_produccion_altas] a
left join [gpper].[dbo].[Peru_Maestro_Articulos] b
on (a.id_producto = b.Codigo)
left join [dbo].[Precio_Inyeccion_soplado] c
on (a.id_producto = c.id_producto)
left join precioabc f
on (a.id_producto = f.id_producto) where a.linea_negocio <> 'extrusion' and a.linea_negocio <> 'reventa'