我有一个表格,其中行代表某个时间点的个人。我正在尝试使用另一列(statusLag
)的滞后值创建一个列(status
),如下所示:
workerID timeVar status statusLag
---------------------------------------------
1 1 0 NULL
1 2 1 0
1 3 1 1
1 4 1 1
----------------------------------------------
2 3 1 NULL
2 4 0 1
2 5 1 0
2 6 0 1
执行以下操作失败(保持列不变),我无法理解为什么
ALTER TABLE myTable ADD COLUMN statusLag INTEGER;
INSERT INTO myTable (statusLag)
SELECT
(SELECT t2.status
FROM myTable t2
WHERE t2.workerID = t1.workerID AND
t2.timeVar < t1.timeVar
ORDER BY t2.timeVar desc
LIMIT 1)
FROM myTable t1;
我几乎通过创建一个新表来实现我想要的目标:
CREATE TABLE myOtherTable
( 'workerID' REAL NOT NULL,
'timeVar' INTEGER NOT NULL,
'statusLag' INTEGER,
PRIMARY KEY('workerID', 'timeVar')
)
INSERT INTO myOtherTable
SELECT t1.workerID, t1.timeVar,
(SELECT t2.status
FROM myTable t2
WHERE t2.workerID = t1.workerID AND
t2.timeVar < t1.timeVar
ORDER BY t2.timeVar desc
LIMIT 1)
FROM myTable t1;
要实现我想要的目标,我需要加入myOtherTable
myTable
。但这对我来说效率很低。
所以我的问题是:为什么我的第一次尝试不起作用?我如何以更有效的方式实现我想要的目标?
答案 0 :(得分:1)
由于您使用信息而不是更新现有行插入了新的行,因此无法正常工作。也许这就是你想要的:
UPDATE myTable
SET statusLag = (SELECT t2.status
FROM myTable t2
WHERE t2.workerID = myTable.workerID AND
t2.timeVar < myTable.timeVar
ORDER BY t2.timeVar desc
LIMIT 1
);