如何在sqlite中使用ROW_NUMBER

hrysbysz  于 2023-01-13  发布在  SQLite
关注(0)|答案(6)|浏览(254)

下面是我的疑问。

select * from data where value = "yes";

我的ID是自动递增的,下面是给定查询的结果。

id || value 
1  ||   yes
3  ||   yes
4  ||   yes
6  ||   yes
9  ||   yes

如何在sqlite中使用ROW_NUMBER?这样我就可以得到下面给出的结果。

NoId || value 
1    ||   yes
2    ||   yes
3    ||   yes
4    ||   yes
5    ||   yes

行号为编号

w8ntj3qf

w8ntj3qf1#

SQLite Release 3.25.0将添加窗口函数支持
2018年9月15日(3月25日)
1.添加对窗口函数的支持
Window Functions
窗口函数是一种特殊的SQL函数,其中的输入值取自SELECT语句结果集中一行或多行的“窗口”。
SQLite支持以下11个内置窗口函数:

行号()

当前分区中的行号。行从1开始按窗口定义中ORDER BY子句定义的顺序编号,否则按任意顺序编号。
因此,您的查询可以重写为:

select *, ROW_NUMBER() OVER(ORDER BY Id) AS NoId
from data 
where value = "yes";

一个月一次

r8xiu3jd

r8xiu3jd2#

尝试以下查询

select id, value, (select count(*) from tbl b  where a.id >= b.id) as cnt
from tbl a

小提琴

| id | value | cnt |
--------------------
|  1 |   yes |   1 |
|  3 |   yes |   2 |
|  4 |   yes |   3 |
|  6 |   yes |   4 |
|  9 |   yes |   5 |
mqxuamgl

mqxuamgl3#

我用fiddleanswer作了一些修改,得到了完全符合预期的结果

select id, value , 
       (select count(*) from data b where a.id >= b.id and b.value='yes') as cnt 
from data a where  a.value='yes';

result
1|yes|1
3|yes|2
4|yes|3
6|yes|4
9|yes|5
ttvkxqim

ttvkxqim4#

更新:sqlite3 3.25版现在支持窗口函数,包括:
row_number()超过(按标识排序)
SQLITE3 Documentation

wz8daaqr

wz8daaqr5#

ROW_NUMBER()窗口函数可以在“NULL”顺序上执行,如下所示:

select *, ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS NoId
from data 
where value = "yes";
e37o9pze

e37o9pze6#

SELECT (SELECT COUNT(*)
FROM main AS t2
WHERE t2.col1 < t1.col1) + (SELECT COUNT(*)
FROM main AS t3
WHERE t3.col1 = t1.col1 AND t3.col1 < t1.col1) AS rowNum, * FROM Table_name t1  WHERE rowNum=0 ORDER BY t1.col1 ASC

相关问题