简体   繁体   中英

SQL Find Previous Value for Each Row

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 (ie user 7 has version 3 and 15 with no versions 4, 5, 6, etc...).

Since you have mentioned that:

The version numbers are not guaranteed to be sequential starting at 1. My actual database has some unusual version numbers (ie user 7 has version 3 and 15 with no versions 4, 5, 6, etc...)

MySQL doesn't support window functions like any other RDBMS does, you can still simulate on how you can create a sequential numbers and used as the linking column to get the previous rows. Ex,

SELECT  a.ID, a.Version, a.attribute attribute_new,
        COALESCE(b.attribute, a.attribute) attribute_old
FROM
        (
            SELECT  ID, version, attribute,
                    @r1 := @r1 + 1 rn
            FROM    TableName, (SELECT @r1 := 0) b
            WHERE   ID = 4
            ORDER   BY version
        ) a
        LEFT JOIN
        (
            SELECT  ID, version, attribute,
                    @r2 := @r2 + 1 rn
            FROM    TableName, (SELECT @r2 := 0) b
            WHERE   ID = 4
            ORDER   BY version
        ) b ON a.rn = b.rn + 1
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;

Sample output ( 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         |
+----+---------+-----------+------+---------------+

If version numbers always increase by 1 , you could:

select  cur.id
,       cur.version
,       cur.attribute
,       coalesce(prev.attribute, cur.attribute)
from    versionTest
left join
        versionTest prev
on      prev.id = cur.id
        and prev.version = cur.version + 1

You could try...

SELECT ID,
       VERSION,
       ATTRIBUTE,
       (SELECT ATTRIBUTE
            FROM VERSIONTEST V3
            WHERE V3.ID = V1.ID AND
                  V3.VERSION = (SELECT MAX(VERSION)
                                    FROM VERSIONTEST V2
                                    WHERE V2.ID = V1.ID AND
                                          V2.VERSION < V1.VERSION)) AS PREVIOUSATTRIBUTE
    FROM VERSIONTEST V1;

provided the version values are in numerical order.

I think the easiest way to express this is with a correlated subquery:

select id, version, attribute as attribute_current,
       (select attribute
        from VersionTest vt2
        where vt2.id = vt.id and vt2.version < vt.version
        order by vt2.version
        limit 1
       ) as attribute_prev
from VersionTest vt

This version would put in NULL as the prev value for the first row. If you really want it repeated:

select id, version, attribute as attribute_current,
       coalesce((select attribute
                 from VersionTest vt2
                 where vt2.id = vt.id and vt2.version < vt.version
                 order by vt2.version
                 limit 1
                ), vt.attribute
               ) as attribute_prev
from VersionTest vt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM