MySQL使用GROUP BY和ORDER BY

时间:2012-10-17 14:41:09

标签: mysql sql group-by sql-order-by

我有一个人员表,每个人都有访问次数优先级

ID | NAME          |  VISITS | PRIORITY
---------------------------------------
 1 |     John      |    1    |   0
 2 |     Joe       |    2    |   1
 3 |     Peter     |    1    |   1
 4 |     Sara      |    0    |   2  
 5 |     Phillip   |    5    |   0
 6 |     Bob       |    3    |   1
 7 |     Andrew    |    4    |   2

只有某些允许的优先级:(0,1,2)

如何创建一个查询,根据访问次数(从最低位置开始),但在相应的优先级组内,按人数排序?

所以结果应该是这样的:

ID | NAME          |  VISITS | PRIORITY
---------------------------------------
 1 |     John      |    1    |   0
 2 |     Philip    |    5    |   0
 3 |     Peter     |    1    |   1
 4 |     Joe       |    2    |   1  
 5 |     Bob       |    3    |   1
 6 |     Sara      |    0    |   2
 7 |     Andrew    |    4    |   2

我想必须使用GROUP BY子句,但我不知道如何使用它。

3 个答案:

答案 0 :(得分:8)

您刚试过ORDER BY

select id, name, visits, priority
from people
order by priority, visits

请参阅SQL Fiddle with Demo

答案 1 :(得分:4)

您将使用ORDER BY和两列。

SELECT * FROM people ORDER BY priority, visits;

答案 2 :(得分:2)

试试这个:

Select * from table order by priority, visits

注意:ID列不会在您的结果上有订单,因为每次访问都有其ID,您的结果应如下所示:

ID | NAME          |  VISITS | PRIORITY
---------------------------------------
 1 |     John      |    1    |   0
 5 |     Philip    |    5    |   0
 3 |     Peter     |    1    |   1
 2 |     Joe       |    2    |   1  
 6 |     Bob       |    3    |   1
 4 |     Sara      |    0    |   2
 7 |     Andrew    |    4    |   2