I have a table where several reporting entitities store several versions of their data (indexed by an integer version number). I created a view for that table that selects only the latest version:
SELECT * FROM MYTABLE NATURAL JOIN
(
SELECT ENTITY, MAX(VERSION) VERSION FROM MYTABLE
GROUP BY ENTITY
)
Now I want to create another view that always selects the one version before the latest for comparison purposes. I thought about using MAX()-1 for this (see below), and it generally works but the problem is that this excludes entries from entities who reported only one version.
SELECT * FROM MYTABLE NATURAL JOIN
(
SELECT ENTITY, MAX(VERSION) - 1 VERSION FROM MYTABLE
GROUP BY ENTITY
)
Edit: for clarity, if there is only one version available, I would like it to report that one. As an example, consider the following table:
ENTITY VERSION VALUE1
10000 1 10
10000 2 11
12000 1 50
14000 1 15
14000 2 16
14000 3 17
Now what I would like to get with my query would be
ENTITY VERSION VALUE1
10000 1 10
12000 1 50
14000 2 16
But with my current query, the entry for 12000 drops out.