获取SQLite表的索引视图中项目的行号

fv2wmkja  于 2023-03-03  发布在  SQLite
关注(0)|答案(1)|浏览(282)

我有一个简单的表
CREATE TABLE MyTable (MyText TEXT UNIQUE ON CONFLICT REPLACE);
我有一个SELECT语句,它按创建时的降序返回表行:
SELECT MyText FROM MyTable ORDER BY rowid DESC;
比如说,它返回

A
B
C

如何获得“B”(本例中为2)在此查询结果中的位置?

pod7payv

pod7payv1#

我和朋友RaptorX聊天时得到了答案:

WITH SortedTable AS (
    SELECT row_number() OVER (ORDER BY rowid DESC) AS RowNum,
           MyText
      FROM MyTable
)
SELECT RowNum
  FROM SortedTable
 WHERE MyText = 'C';

或者这个一行的版本:
SELECT RowNum FROM (SELECT row_number() OVER (ORDER BY rowid DESC) AS RowNum, MyText FROM MyTable) WHERE MyText = 'C';

相关问题