Abanoub Samaan Abanoub Samaan - 3 months ago 7
MySQL Question

i want to get the most visited 5 sections desc ordered

lets assume that i have this MySql table structure

+----+------------+-------+
| id | section_id | views |
+----+------------+-------+
| 1 | 2 | 15 |
+----+------------+-------+
| 2 | 2 | 12 |
+----+------------+-------+
| 3 | 1 | 15 |
+----+------------+-------+
| 4 | 3 | 60 |
+----+------------+-------+
| 5 | 2 | 100 |
+----+------------+-------+
| 6 | 2 | 20 |
+----+------------+-------+
| 7 | 4 | 14 |
+----+------------+-------+
| 8 | 5 | 60 |
+----+------------+-------+
| 9 | 6 | 12 |
+----+------------+-------+
| 10 | 1 | 17 |
+----+------------+-------+


i want to get the most visited 5 sections desc ordered

i have tried
SELECT section_id FROM my_table ORDER by VIEWS DESC LIMIT 5
and have tried some other things like
sum()
but finally i got confused because i haven't use MySql for long time

your help is very appreciated

Answer

SQL:

  SELECT section_id, SUM(views)
    FROM my_table
GROUP BY section_id
ORDER BY SUM(views) DESC
   LIMIT 5

Result:

section_id  sum(views)
2           147
3           60
5           60
1           32
4           14

Playground:

http://sqlfiddle.com/#!9/6e3266/3/0