I have this table:
+----+------------+-----------+
| ID | VALID_FROM | VALID_TO |
+----+------------+-----------+
| A | 28-JUN-19 | 28-JUN-19 |
+----+------------+-----------+
| A | 28-JUN-19 | 29-JUN-19 | //penultimo de A
+----+------------+-----------+
| A | 28-JUN-19 | 30-JUN-19 | //ultimo de A
+----+------------+-----------+
| B | 28-JUN-19 | 30-JUN-19 | // lo ignoramos
+----+------------+-----------+
| C | 27-JUN-19 | 28-JUN-19 |
+----+------------+-----------+
| C | 28-JUN-19 | 28-JUN-19 |
+----+------------+-----------+
| C | 28-JUN-19 | 29-JUN-19 |
+----+------------+-----------+
| C | 29-JUN-19 | 30-JUN-19 | //penultimo de C
+----+------------+-----------+
| C | 29-JUN-19 | 01-JUL-19 | //ultimo de C
+----+------------+-----------+
I need a query that for each present group A,B,C
returns me the records in which the VALID_FROM
last element of a group is GREATER VALID_TO
than the penultimate element of that same group`.
If a group has only one row then the comparison is not made (AS IN THE CASE OF B).
The query I created is this:
SELECT *
FROM
myTabla g1
INNER JOIN
myTabla g2 ON g2.valid_from > g1.valid_to
WHERE
g1.ID = g2.ID;
I don't know if the logic is correct, and I don't know how to make the comparison only between the last and penultimate of each group.
To obtain the last and penultimate record by [ID], a field is required to sort them, in this case use the [N_REGISTER] column with a consecutive number, it could also be a datetime field.
In the example of the query there are no records that meet the requested condition, so the group "D" was entered in the sample data of this response.