SQL 查询在主 select 查询中获取行排名或位置
SQL Query get row rank or position on the main select query
我正在尝试从我的 SELECT
查询中获取特定行的排名。
这是我的 table :
| PID | Age |
|------ |----- |
| 5295 | 27 |
| 4217 | 26 |
| 2935 | 25 |
| 8706 | 24 |
我的查询和代码:I'm using SQL Server
$x = 0;
$query = odbc_exec($connect, "SELECT * FROM mytable ORDER BY Age DESC"); // Ordering by "Age" Descending
while($row = odbc_fetch_array($query)) {
$x++;
if($row['PID'] == 2935) { break; // Stop }
}
echo $x; // output "3"
这个方法有效,但问题是这可以通过简单的独立 SQL Query
而不是 looping
完成所有结果,然后递增 $x
变量以获得 [=19= 】 排名。因为此 table 包含数千个条目,在循环时会有点滞后,直到找到所需的行然后停止循环。
这个排名的逻辑,因为我用 Age
降序排列,所以例如它将从 27
开始,排名 1
到 24
排名 4
.
我怎样才能做到这一点?
您可以在子查询中使用row_number()
为每条记录分配一个排名,然后在您感兴趣的行的外部查询中过滤掉:
select *
from (
select t.*, row_number() over(order by age desc) rn
from mytable t
) t
where pid = 2935
在MySQL中,window函数仅支持8.0版本。在SQL服务器中,它们已经存在很长时间了。
我正在尝试从我的 SELECT
查询中获取特定行的排名。
这是我的 table :
| PID | Age |
|------ |----- |
| 5295 | 27 |
| 4217 | 26 |
| 2935 | 25 |
| 8706 | 24 |
我的查询和代码:I'm using SQL Server
$x = 0;
$query = odbc_exec($connect, "SELECT * FROM mytable ORDER BY Age DESC"); // Ordering by "Age" Descending
while($row = odbc_fetch_array($query)) {
$x++;
if($row['PID'] == 2935) { break; // Stop }
}
echo $x; // output "3"
这个方法有效,但问题是这可以通过简单的独立 SQL Query
而不是 looping
完成所有结果,然后递增 $x
变量以获得 [=19= 】 排名。因为此 table 包含数千个条目,在循环时会有点滞后,直到找到所需的行然后停止循环。
这个排名的逻辑,因为我用 Age
降序排列,所以例如它将从 27
开始,排名 1
到 24
排名 4
.
我怎样才能做到这一点?
您可以在子查询中使用row_number()
为每条记录分配一个排名,然后在您感兴趣的行的外部查询中过滤掉:
select *
from (
select t.*, row_number() over(order by age desc) rn
from mytable t
) t
where pid = 2935
在MySQL中,window函数仅支持8.0版本。在SQL服务器中,它们已经存在很长时间了。