Find the year in which total customers (sum) was higher

Asked

Viewed 32 times

0

I’m using sqlite, and I have a table like:

year | clients    
---- | -------                                                            
2000 | 1                                                                              
2000 | 2  
1999 | 3                                                                      
1999 | 5  
2000 | 4                                                                      
1999 | 6

This is just one example. I want to find the year when the total of customers was higher.

The best I could do was to separate for each year, add up the clients, and present each year with the respective sum. But I don’t know how to present only the year it was greatest.

I want to present the year and total customers. That is to say:

1999 | 14                                                                     

I used:

select year, sum(clients) from table group by year;

I’ve tried too

select year, max(sum(clients)) from table group by year;
  • This is [en.so], the questions and answers here need to be on portuguese. You can [Dit] your question and translate it.

  • It’s already translated. Thanks for formatting the text, I’m a turnip in this xD

  • You can use the LIMIT clause: select year, sum(clients) from table group by year order by sum(clients) DESC limit 1;

  • Quiet. There is a formatting guide that you can always use.

1 answer

3


The first select is correct according to the result example you put in the question.

If the table name is really table (by the way, the name is terrible) you should escape the name using backticks because this is a reserved word. That is, it is necessary to use `table` instead of table.

If you need to present only the first result, use limit 1 at the end of query. In this case, it is a good idea to force ordering by the column in which the client sum is made.

select year, sum(clients) as soma 
from `table`
group by year 
order by soma desc
limit 1

See working on Sqlfiddle.

  • Of course, table was just an example. Thanks for the help! However, the first select presents the two years and their sums. That’s not what I want. I want to present only 1999 (since the sum is greater).

  • That’s not what you said in the question (in your expected output example shows the two years). Anyway just add LIMIT 1 at the end of the query.

  • @Artichoke I updated the answer.

  • You’re right. I’ve updated the question too. Thank you. Great the answer! Or I’m a turnip ahahah

Browser other questions tagged

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