I have a table where the values can be repeated in each year (or not), I need to collect only the references of the last year with their values in the event that they are repeated in different periods.
Period | Reference | Value1 | Value2 |
---|---|---|---|
2020 | REF1 | C1 | C2 |
2020 | REF2 | C2 | C3 |
2020 | REF3 | C0 | C3 |
2021 | REF1 | C11 | C22 |
2021 | REF2 | C22 | C33 |
2021 | REF4 | C0 | C3 |
I want to get this unique filtering taking into account the closest year:
Period | Reference | Value1 | Value2 |
---|---|---|---|
2020 | REF3 | C0 | C3 |
2021 | REF1 | C11 | C22 |
2021 | REF2 | C22 | C33 |
2021 | REF4 | C0 | C3 |
How could I do it?
Here is my last test, but it keeps thinking for more than 3 minutes and finally I cancel it, I need to do it in a few seconds.
SELECT df.* FROM datosfase df,
(
SELECT MAX(PERIODO) AS PERIODO, REFERENCIA
FROM datosfase
GROUP BY REFERENCIA
ORDER BY PERIODO DESC
) t1
WHERE df.PERIODO = t1.PERIODO AND df.REFERENCIA= t1.REFERENCIA