Given the query:
SELECT MAX(fecha), estado
FROM tabla
GROUP BY estado
I get the maximum date of the table for each state.
My question is: Can I get the columns that are not in the Group By without making aggregations? that is:
SELECT MAX(fecha), estado, id
FROM tabla
GROUP BY estado
Where would I like the id to be the concrete id of the row that is being selected with MAX(fecha)
.
If the tabla
table contains:
id - date - state
1 - 03/11/1991 - Open
2 - 03/11/1992 - Open
3 - 03/11/1993 - Open
4 - 03/11/1992 - Closed
5 - 03/11/1991 - Closed
If you applied the first query, you would get:
03/11/1993, Open
03/11/1992, Closed
And I would like to get:
03/11/1993, Open, 3
03/11/1992, Closed, 4
I understand that there is an additional problem in the case that more than 1 row has the same date and status, which would cause the id to be random but it would be useful to anyone. That is, if the table contains:
id - date - state
1 - 03/11/1991 - Open
2 - 03/11/1992 - Open
3 - 03/11/1993 - Open
4 - 03/11/1992 - Closed
5 - 03/11/1991 - Closed
6 - 03/11/1992 - Closed
The result serves me so much this:
03/11/1993, Open, 3
03/11/1992, Closed, 4
How is this:
03/11/1993, Open, 3
03/11/1992, Closed, 6
But if there is any better way to work with it I would like to learn it.