I want to retrieve a record where the age group is greater than 50 and show the top 2 month.
x
So, this is my table with 3 column
Age_group infection Month
30-39 50 2
40-49 11 1
40-49 18 4
50-59 27 2
60-69 30 4
50-59 5 3
70-79 23 3
50-59 4 1
The result should return like this:
Month
4
3
As we can see in the age_group there is 2 row fall in month ‘3’. The total value in month ‘3’ is 28. And the another month which have the greater value is month ‘4’
Advertisement
Answer
You must group by month
and sum the infections before you sort and return the top2:
select month, sum(infection) total_infection
from tablename
where age_group > '50'
group by month
order by total_infection desc
limit 2
See the demo.
Results:
| Month | total_infection |
| ----- | --------------- |
| 4 | 30 |
| 3 | 28 |