Select order by desc 时 SQLITE 中的行号 X
Select the row number X in SQLITE when order by desc
我正在使用 SQLITE(所以没有 row_number)
这是我的数据库调用:tableau
ID | Nom | Score
---|------|------
1 | Clem | 50
2 | Caro | 60
3 | Flo | 55
我正在使用:
SELECT * FROM tableau ORDER BY Score DESC
这是我得到的:
ID | Nom | Score
---|------|------
2 | Caro | 60
3 | Flo | 55
1 | Clem | 50
但我想在按降序排序后获得第 2 行的 "Nom" 值
我想使用 :
SELECT Nom FROM tableau WHERE rowid = 2 ORDER BY Score DESC
但结果是 "Caro"(预期结果:"Flo")
不幸的是,SQLite 不支持 window 函数或变量,这两种方法将在其他数据库中使用。处理这个问题的最好方法通常是在应用层
您可以获得一行的排名,然后使用它:
select t.*
from (select t.*,
(select 1 + count(*)
from tableau t2
where t2.score > t.score
) as rnk
from tableau t
) t
where rnk = 2;
请注意,这会使并列得分具有相同的排名。
请注意,您也可以将其表述为:
select t.*
from tableau t
where 2 = (select 1 + count(*)
from tableau t2
where t2.score > t.score
);
编辑:
如果你想要一个稳定的排序,你必须在逻辑中包含它:
select t.*
from tableau t
where 2 = (select 1 + count(*)
from tableau t2
where t2.score > t.score or
(t2.score = t.score and t2.name < t.name)
);
我正在使用 SQLITE(所以没有 row_number)
这是我的数据库调用:tableau
ID | Nom | Score
---|------|------
1 | Clem | 50
2 | Caro | 60
3 | Flo | 55
我正在使用:
SELECT * FROM tableau ORDER BY Score DESC
这是我得到的:
ID | Nom | Score
---|------|------
2 | Caro | 60
3 | Flo | 55
1 | Clem | 50
但我想在按降序排序后获得第 2 行的 "Nom" 值
我想使用 :
SELECT Nom FROM tableau WHERE rowid = 2 ORDER BY Score DESC
但结果是 "Caro"(预期结果:"Flo")
不幸的是,SQLite 不支持 window 函数或变量,这两种方法将在其他数据库中使用。处理这个问题的最好方法通常是在应用层
您可以获得一行的排名,然后使用它:
select t.*
from (select t.*,
(select 1 + count(*)
from tableau t2
where t2.score > t.score
) as rnk
from tableau t
) t
where rnk = 2;
请注意,这会使并列得分具有相同的排名。
请注意,您也可以将其表述为:
select t.*
from tableau t
where 2 = (select 1 + count(*)
from tableau t2
where t2.score > t.score
);
编辑:
如果你想要一个稳定的排序,你必须在逻辑中包含它:
select t.*
from tableau t
where 2 = (select 1 + count(*)
from tableau t2
where t2.score > t.score or
(t2.score = t.score and t2.name < t.name)
);