In my view there is an error in your modeling, consider reviewing, because you do not record the value of the product in the sales table, imagine the following scenario:
In your product list the value of the pen is $ 2,00, you make a sale today from the last pen in stock, and the next day the buyer of your company buys a new batch of the same pen, but for a higher price, then your sale price ceases to be $ 2,00 and becomes $ 2,50, If you use as reference the value registered in the product table to determine the value of your billing, all pens that have already been sold will assume the new value that is $ 2,50;
The sales table represents a fact, and you should store the value of the product in it, it will help you answer questions like:
2.1 How much did the pen cost in 2020?
2.1 Average pen value over the last 6 months;
Also only then will you get the real value of your billing.
Anyway I understood your question, follow the query I believe is what you need, when you change your modeling, just change b. price for a. value where value will correspond to the value of the product at the time of sale.
Below Query idea based on your problem:
- Perform the Join between the sales table and product;
- Add the total value of "sale" by product;
- Sort decreasingly (Larger to smaller);
- Limit the result;
This template is cool because you can make your query more versatile, and just by manipulating the limit, you could show the 5 products with higher billing value for example.
I hope I’ve helped
select b.codigo, b.descricao_prod, sum(b.preco) as vltotal
from venda a inner join produto b on (a.cod_prod = b.codigo)
group by b.codigo, b.descricao_prod
order by vltotal desc
limit 1;
Could add the DDL of the tables and an example of the expected output?
– Danizavtz
In this modeling there is a possible error, in the sales table should be stored the value of the product at the time it was sold, this is because the product may suffer change in values, the sales table also serves as a history, I recommend that you perform this adjustment, anyway I will put the answer based on your current modeling.
– Raphael Godoi