表三列id,numers1和number2。我们需要总结numers1和number2,但第一行到第二行numers1 numers2第二行有第三行和第三行等等。
CREATE TABLE tb1 (id INTEGER PRIMARY KEY AUTOINCREMENT,numbers1,numbers2);
INSERT INTO tb1 (numbers1,numbers2) values(1,10);
INSERT INTO tb1 (numbers1,numbers2) values(2,20);
INSERT INTO tb1 (numbers1,numbers2) values(3,30);
INSERT INTO tb1 (numbers1,numbers2) values(4,40);
INSERT INTO tb1 (numbers1,numbers2) values(5,50);
我想得到:
21
32
43
54
答案 0 :(得分:0)
在此处获取每条记录的正确行索引的引用: How to use ROW_NUMBER in sqlite
我能够使用以下查询创建所需的结果:
SELECT
num1 + coalesce(b_num2, 0)
FROM(
SELECT
num1,
(select count(*) from test as b where a.id >= b.id) as cnt
FROM test as a) as a
LEFT JOIN
(SELECT num2 as b_num2,
(select count(*) from test as b where a.id >= b.id) as cnt
FROM test as a
) as b
ON b.cnt = a.cnt + 1
说明:
通过连接两个相似记录索引的相同表,然后将下一条记录与当前记录合并,然后将当前记录的num1与下一条记录的num2相加,我不知道你想如何处理最后一行,因为它没有下一行所以我假设它没有添加任何只有num1
的值的结果结果:
答案 1 :(得分:0)
对于具有特定ID x
的一行,您可以通过搜索大于x
的ID值并获取第一行来获取下一行中的值:
SELECT ...
FROM tb1
WHERE id > x
ORDER BY id
LIMIT 1;
然后,您可以将其用作correlated subquery来获取每一行的值:
SELECT numbers1 + (SELECT T2.numbers2
FROM tb1 AS T2
WHERE T2.id > T1.id
ORDER BY T2.id
LIMIT 1) AS sum
FROM tb1 AS T1
WHERE sum IS NOT NULL; -- this omits the last row, where the subquery returns NULL