List the 10 best selling products

-1

I need to list the 10 best selling products in a table using Hibernate.

The item_venda table has the following columns:

  • quantity
  • product_id
  • community_value
  • value_sub_Total
asked by anonymous 03.09.2016 / 16:36

1 answer

6

The best-selling items would be those most present in the item_venda table. In this case, you would only need to create the SQL query by sorting the items by sum of quantity per product, i.e. by the number of occurrences of a product considering its quantity in the item_vend table. The sql would look like:

select sum(quantidade), id_produto from item_venda group by id_produto
order by sum(quantidade) desc;

Okay, now you have the ids of the best-selling products in descending order (the first best seller, the least sold later). Now if you need other top-selling product information just create a subquery to bring them based on the ids you've retrieved:

select * from produto p join
(select sum(quantidade), id_produto from item_venda group by id_produto
order by sum(quantidade) desc) itensMaisVendidos on (p.id = itensMaisVendidos.id_produto)

Now, what was done in the above query was to first bring all the products and then count the sale of each of them through sum and group by. Using the join is done comparing the id of the product with the id of the best-selling product, so no repeated results will appear due to the Cartesian product made through the join between the tables.

    
03.09.2016 / 16:50