How to get the largest sum on a table?

Asked

Viewed 144 times

0

have a table

id  produto  vendas      data
 1  laranja     4     16-10-2016
 2  cenoura     3     16-10-2016
 3  cenoura     6     17-10-2016
 4  laranja     5     17-10-2016
 5  laranja     1     18-10-2016
 6  laranja     1     19-10-2016

the sum of oranges in 11 the carrot sum of the 9... How do I make the answer to be orange 11(take the best selling item and the sum)??

1 answer

1

Grouping the results, adding and picking the first item:

SELECT produto, SUM(vendas) AS total_vendas
FROM produtos
GROUP BY produto             -- agrupando pelo nome (o ideal seria id)
ORDER BY SUM(vendas) DESC    -- ordenando por soma, da maior para a menor
LIMIT 1;                     -- pegando apenas o primeiro resultado

See working on SQL Fiddle

  • Limit 1 would be to catch only the biggest, if put 2 will catch the biggest 2?

  • Yes. If you do not place LIMIT you will get all, from the best seller to the least sold.

  • But with that and I can’t figure out which product sold the most.

  • for me here only appears the sum of the product best sold, but does not say which product is

  • Must have produto in select, as in my example, right at the start

  • @Daneven I put a link to a functional example for you to see, with LIMIT commented.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.