I have a database (attached BD open BD to import ), in where I want to get a report in which I take out the sale list of each product in invoices, showing how much I sold it and how much it cost me. The problem is that the query I get:
SELECT p.id, p.descripcion, (vp.valor * vp.cantidad) as valor_total, fv.id ,fv.fechaventa, fc.id as fc_id ,fc.fecha_compra, (pc.precio_compra * vp.cantidad)
FROM venta_producto vp
inner join factura_venta fv on fv.id = vp.id_venta
inner join producto p on p.id = vp.id_producto
left join producto_compra pc on pc.id_producto = p.id
left join factura_compra fc on fc.id = pc.id_compra and fc.fecha_compra < fv.fechaventa
group by fv.id, p.id
ORDER BY p.id, fv.id ASC
and fc.date_purchase < fv.fechaventa The problem is that I have many date_buying less than the sale date and the query takes the lowest of all and not the smallest immediately (the most recent date from the previous to date sale) That is, it puts the first purchase price of the entire database as the purchase price.
the query, I want to do it to compare as soon as it was sold and how much I cost (you may have already bought that product again After the sale when you want to generate the report, then you must take out not the last purchase, if not the last purchase before selling)