我希望得到最受欢迎的5个部分desc订购

时间:2016-08-16 21:50:07

标签: mysql sql

假设我有这个MySql表结构

+----+------------+-------+
| 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  |
+----+------------+-------+

我希望得到最受欢迎的5个部分desc命令

我已经尝试SELECT section_id FROM my_table ORDER by VIEWS DESC LIMIT 5并尝试了其他一些事情,例如sum()但最后我感到困惑,因为我很长时间没有使用MySql

非常感谢您的帮助

2 个答案:

答案 0 :(得分:1)

SQL:

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

结果:

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

游乐场:

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

答案 1 :(得分:0)

如果您不想要id字段,则使用group by语句进行聚合并限制在一起。

SELECT section_id, SUM(Views) as Views
FROM
     my_table
GROUP BY
    section_id
ORDER by
   VIEWS DESC
LIMIT 5;