I have a SQL table with the following structure:
id Integer, (represents a userId)
version Integer,
attribute varchar(50)
So some sample rows are:
4, 1, 'test1'
4, 2, 'test2'
4, 3, 'test3'
I need to generate output in the following format:
4, 1, 'test1', 'test1'
4, 2, 'test2', 'test1'
4, 3, 'test3', 'test2'
So the format of my output would be:
id Integer,
version Integer,
attribute_current varchar,
attribute_old varchar
I already tried the following:
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);
The above query executes, but returns incorrect results. It only returns the largest version instead of returning rows for all versions.
Any ideas about how I should fix my query to produce the correct results? Thanks!
Note - The version numbers are not guaranteed to be sequential starting at 1. My actual database has some unusual version numbers (i.e. user 7 has version 3 and 15 with no versions 4, 5, 6, etc...).