2

我有一张人桌,每个人都有访问次数优先级

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 子句,但我不确定如何使用它。

4

3 回答 3

8

您是否尝试过ORDER BY

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

请参阅带有演示的 SQL Fiddle

于 2012-10-17T14:43:17.227 回答
4

您将使用 ORDER BY 和两列。

SELECT * FROM people ORDER BY priority, visits;
于 2012-10-17T14:43:20.937 回答
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
于 2012-10-17T14:46:43.210 回答