我有一个具有以下结构的 SQL 表:
id Integer, (represents a userId)
version Integer,
attribute varchar(50)
所以一些示例行是:
4, 1, 'test1'
4, 2, 'test2'
4, 3, 'test3'
我需要生成以下格式的输出:
4, 1, 'test1', 'test1'
4, 2, 'test2', 'test1'
4, 3, 'test3', 'test2'
所以我的输出格式是:
id Integer,
version Integer,
attribute_current varchar,
attribute_old varchar
我已经尝试过以下方法:
select versionTest.id, versionTest.version, versionTest.attribute, maxVersionTest.attribute
from versionTest
inner join
versionTest maxVersionTest
ON
versionTest.id = versionTest.id
AND
versionTest.version =
(Select max(version) currentMaxVersion
from versionTest maxRow
where maxRow.id = id);
上述查询执行,但返回不正确的结果。它只返回最大的版本,而不是返回所有版本的行。
关于我应该如何修复我的查询以产生正确结果的任何想法?谢谢!
注意 - 版本号不能保证从 1 开始是连续的。我的实际数据库有一些不寻常的版本号(即用户 7 有版本 3 和 15,没有版本 4、5、6 等...)。
最佳答案
SELECT a.*, COALESCE(b.attribute,a.attribute) attribute_old
FROM
( SELECT x.*
, COUNT(*) rank
FROM versiontest x
JOIN versiontest y
ON y.id = x.id
AND y.version <= x.version
GROUP
BY x.id
, x.version
) a
LEFT
JOIN
( SELECT x.*
, COUNT(*) rank
FROM versiontest x
JOIN versiontest y
ON y.id = x.id
AND y.version <= x.version
GROUP
BY x.id
, x.version
) b
ON b.id = a.id
AND b.rank = a.rank-1;
样本输出(DEMO):
+----+---------+-----------+------+---------------+
| id | version | attribute | rank | attribute_old |
+----+---------+-----------+------+---------------+
| 4 | 1 | test1 | 1 | test1 |
| 4 | 5 | test2 | 2 | test1 |
| 4 | 7 | test3 | 3 | test2 |
| 5 | 2 | test3 | 1 | test3 |
| 5 | 3 | test4 | 2 | test3 |
| 5 | 8 | test5 | 3 | test4 |
+----+---------+-----------+------+---------------+
关于mysql - SQL 为每一行查找以前的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16192877/