因此,我编写的查询与this answer中描述的查询几乎相同。但是,我收到一条错误消息,指出:没有这样的列b.when
。
我的选择语句:
SELECT
mileage,
(SELECT b.mileage FROM MileageEvents as b WHERE `b.when` < `a.when` ORDER BY `b.when` DESC LIMIT 1) as last_mileage,
gallons,
cost_per_gallon,
`when`
FROM MileageEvents as a
我知道我以前已经写过这样的查询,但是我似乎无法弄清楚此查询的情况。我在做什么错了?
我的数据库转储:
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE IF NOT EXISTS "MileageEvents" (
"mileage" INTEGER,
"when" TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
"cost_per_gallon" INTEGER,
"gallons" INTEGER,
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"car_id" INTEGER NOT NULL
);
INSERT INTO MileageEvents VALUES(150000,'2019-03-12',3.3500000000000000888,12,1,1);
INSERT INTO MileageEvents VALUES(150300,'2019-03-19',3.25,12,2,1);
INSERT INTO MileageEvents VALUES(150693,'2019-03-22',3.4500000000000001776,12,3,1);
INSERT INTO MileageEvents VALUES(151000,'2019-03-25',3.3900000000000001243,12,4,1);
INSERT INTO MileageEvents VALUES(151600,'2019-04-01',2.25,12,5,1);
INSERT INTO MileageEvents VALUES(151883,'2019-06-10 23:01:43',2.4500000000000001776,11.695999999999999729,6,1);
DELETE FROM sqlite_sequence;
INSERT INTO sqlite_sequence VALUES('MileageEvents',6);
COMMIT;
答案 0 :(得分:2)
(首先,我将使用普通的双引号转义而不是MySQL样式的反引号,或者更好的是,该标识符不是保留关键字)
您需要使用b."when"
。您正在执行的操作将整个字符串b.when
视为标识符,而表名和列名之间没有分隔。
重写:
SELECT
mileage,
(SELECT b.mileage FROM MileageEvents as b WHERE b."when" < a."when" ORDER BY b."when" DESC LIMIT 1) as last_mileage,
gallons,
cost_per_gallon,
"when"
FROM MileageEvents as a;
注意:如果使用sqlite 3.25或更高版本,则可以完全避免子查询:
SELECT
mileage,
lag(mileage) OVER (ORDER BY "when") AS last_mileage,
gallons,
cost_per_gallon,
"when"
FROM MileageEvents;